Deep and Shallow copy in JavaScript

Deep copy and Shallow copy of an object is an important aspects of JavaScript and as a developer, it is useful to understand this concept.

Let’s declare an object.

let obj1 = {x: 2, y: 3}
obj2 = obj1;

Shallow Copy: It makes a copy of the reference to ‘obj1’ into ‘obj2’. Think about it as a copy of obj1’s Address. So, the addresses of ‘obj1’ and ‘obj2’ will be the same i.e. they will be pointing to the same memory location.

// Shallow Copy: The value of obj1 changes
obj2 = obj1;
obj2.x = 5;
console.log(obj1, obj2); // {x: 5, y: 3} {x: 5, y: 3}

Here, the value of ‘x ’ changes in both ‘obj1 ’and ‘obj2’.

Deep copy: It makes a copy of all the members of ‘obj1’, allocates different memory location for ‘obj2’, and then assigns the copied members to ‘obj2’ to achieve deep copy. In this way, if ‘obj1’ vanishes ‘obj2’ is still valid in the memory.

Method 1: We can use Object.assign() for deep copying.

obj1 = {x: 5, y: 3}
// Deep Copy: The values of obj1 remains unchanged
// Method 1: Use Object.assign()
obj3 = Object.assign({}, obj1);
obj3.x = 56;
console.log(obj1, obj3); // {x: 5, y: 3} {x: 56, y: 3}

Here, we can see that the values of ‘obj1’ don’t change. The value of ‘obj3’ changes.

Method 2: We can also use JSON.parse and JSON.stringify to achieve the same result.

obj1 = {x: 5, y: 3}
// Deep Copy: The values of obj1 remain unchanged
// Method 2: Use JSON.parse(JSON.stringify())
obj4 = JSON.parse(JSON.stringify(obj1));
obj4.x = 10;
console.log(obj1, obj4); // {x: 5, y: 3} {x: 10, y: 3}

To sum it up here is the entire code.

<script>
  let obj1, obj2, obj3, obj4;
  // Shallow Copy and Deep Copy
  obj1 = {
      x: 2,
      y: 3
  }   

  // Shallow Copy: The values of obj1 changes
  obj2 = obj1;
  obj2.x = 5;
  console.log(obj1, obj2); // {x: 5, y: 3} {x: 5, y: 3}

  // Deep Copy: The values of obj1 remain unchanged
  // Method 1: Use Object.assign()
  obj3 = Object.assign({}, obj1);
  obj3.x = 56;
  console.log(obj1, obj3); // {x: 5, y: 3} {x: 56, y: 3}

  // Method 2: Use JSON.parse(JSON.stringify())
  obj4 = JSON.parse(JSON.stringify(obj1));
  obj4.x = 10;
  console.log(obj1, obj4); // {x: 5, y: 3} {x: 10, y: 3}
</script>