Shallow and Deep copy in JavaScript

Shallow and Deep copy in JavaScript

Shallow Copy

Shallow copy creates copy of an object. New copy has exact copy of values in original object. New copy refers to same reference as original object refers.

shallow-copy.png

Example:

let obj = {
  name: "John",
  age: "25"
};

let newObj = obj;

newObj.name = "Tom";

console.log(newObj.name); // "Tom"

console.log(obj.name); // "Tom"

Here it's a shallow copy as changing value of newObj.name changes value of obj.name value also. It creates problems when we don't want change in value of object but we change it's value while creating copy of it.

Deep Copy

Deep copy also create copy of object. But unlike shallow copy new copy does not refer same reference object as original object refers.

deep-copy.png

Examples:

There are some ways to create deep copy

Spread Operator:

let obj = {
  name: "John",
  age: "25"
};

let newObj = {...obj};

newObj.name = "Tom";

console.log(newObj.name); // "Tom";

console.log(obj.name); // "John"

Object.assign():

let obj = {
  name: "John",
  age: "25"
};

let newObj = Object.assign({}, obj);

newObj.name = "Tom";

console.log(newObj.name); // "Tom";

console.log(obj.name); // "John"

Both of the above method are not gonna work for nested objects inside object. When we have nested objects and we copy it, nested objects inside objects are not copied they point to same reference as the original one.

We can either manually deep copy nested objects inside objects or we can stringify() them and parse it.

Example:

let obj = {
  name: "John",
  age: "25",
  address: {
     city: "London",
     country: "UK"
  }
};

let newObj = JSON.parse(JSON.stringify(obj));

newObj.address.city = "Bristol";

console.log(newObj.address.city); // "Bristol";

console.log(obj.address.city); // "London"

Here changing value of newObj.address.city is not gonna change obj.address.city value.

While making copy we need to be careful we might mutate original value and end up getting errors, knowing about deep and shallow copy helps while debugging errors.