Deep vs Shallow Copy in JS

In JavaScript, when working with objects and arrays, you can create a copy of them using either shallow or deep copy.

Shallow copy creates a new object or array but its inner objects or arrays are not copied, instead they are just referenced to the original object. So any changes made to the inner objects of the original object will also reflect in the copied object.

On the other hand, deep copy creates a new object or array as well as copies its inner objects and arrays. Any changes made to the inner objects of the original object will not affect the copied object.

In JavaScript, when working with objects and arrays, you can create a copy of them using either shallow or deep copy.

Shallow copy creates a new object or array but its inner objects or arrays are not copied, instead they are just referenced to the original object. So any changes made to the inner objects of the original object will also reflect in the copied object.

On the other hand, deep copy creates a new object or array as well as copies its inner objects and arrays. Any changes made to the inner objects of the original object will not affect the copied object.

Here are some examples to illustrate the difference between shallow and deep copy:

Shallow Copy

// Original object
const originalObj = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    state: "NY"
  }
};

// Shallow copy
const shallowCopyObj = Object.assign({}, originalObj);

// Change inner object of original object
originalObj.address.city = "Los Angeles";

// Log shallow copied object
console.log(shallowCopyObj);
// Output: { name: "John", age: 30, address: { city: "Los Angeles", state: "NY" } }

As you can see, changing the inner object of the original object also changed the inner object of the shallow copied object. This is because the inner object is only referenced in the shallow copied object.

Deep Copy

// Original object
const originalObj = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    state: "NY"
  }
};

// Deep copy
const deepCopyObj = JSON.parse(JSON.stringify(originalObj));

// Change inner object of original object
originalObj.address.city = "Los Angeles";

// Log deep copied object
console.log(deepCopyObj);
// Output: { name: "John", age: 30, address: { city: "New York", state: "NY" } }

In this example, a deep copy of the original object is created using JSON.parse(JSON.stringify(originalObj)). This creates a new object and copies all the properties of the original object as well as its inner objects and arrays. Therefore, changing the inner object of the original object does not affect the deep copied object.

Leave a Reply

Your email address will not be published. Required fields are marked *