Shallow vs Deep Clone

In general, when we copy things and whenever we make changes, we expect the original thing to stay the same, whereas the copy changes.

Copy Primitive Data Types

When you make a copy, it will be a real copy

const a = 5
let b = a
b = 6
console.log(b) // 6
console.log(a) // 5

Copy Objects

When we assign variable to an object, it just creates a pointer (reference) to that value. So if make a copy b = a, changes in "b" will also impact "a" as well since "a" and "b" actually point to the same thing.

let obj = {one: 1, two: 2};
let obj2 = obj;
console.log(
  obj,  // {one: 1, two: 2};
  obj2  // {one: 1, two: 2};
)

obj2.three = 3;
console.log(obj); // {one: 1, two: 2, three: 3}; <-- 😱
console.log(obj2); // {one: 1, two: 2, three: 3}; <-- ✅

So, there are three ways to copy an object:

Shallow Clone vs Deep Clone of Nested Object

A deep clone means that all of the values of the new variable are copied and disconnected from the original variable, for example, JSON. A shallow clone means that certain (sub-)values are still connected to the original variable, for example, spread operator.

When you have a nested object (or array) and you copy it, nested objects inside that object will not be copied, since they are only pointers / references. In summary, a shallow copy means the first level is copied, deeper levels are referenced. The deep clone is a true copy for nested objects.

Copy Arrays

Copying arrays is just as common as copying objects. A lot of the logic behind it is similar, since arrays are also just objects under the hood.

Last updated

Was this helpful?