The clone
function is used to deep copy an object or array.
It is different from the ES6 spread operator. Spreading only creates a shallow copy. In other words, if there are nested objects or arrays as values in the source object, their reference is copied to the new object while applying the spread operator.
It can be seen with an example.
So, in this case, if we change newObj.b.c
, obj.b.c
changes as well. To make a deep copy we would need to do as follows:
In case the nesting goes deeper, the code starts becoming harder to read. With clone
we can simply write as shown: