What is shallow copy and deep copy in JavaScript?

In JavaScript, a shallow copy is a copy of an object that contains references to the same objects as the original object, rather than copies of the objects themselves. This means that if you modify a property of the original object, the change will also be reflected in the shallow copy.

For example:

let original = { name: 'John', address: { city: 'London' } };
let shallowCopy = { ...original };

original.address.city = 'Paris';
console.log(shallowCopy.address.city); // 'Paris'

In this code, a shallow copy shallowCopy of the original object original is created using the spread operator .... When the city property of the address object in the original object is changed to 'Paris', the change is also reflected in the shallow copy.

A deep copy, on the other hand, is a copy of an object that contains copies of the objects themselves, rather than references to the same objects. This means that changes made to the original object will not affect the deep copy.

For example:

let original = { name: 'John', address: { city: 'London' } };
let deepCopy = JSON.parse(JSON.stringify(original));

original.address.city = 'Paris';
console.log(deepCopy.address.city); // 'London'

In this code, a deep copy deepCopy of the original object original is created by using the JSON.stringify and JSON.parse methods. When the city property of the address object in the original object is changed to 'Paris', the deep copy remains unchanged and still shows the original value 'London'.

In summary, a shallow copy is a copy of an object that contains references to the same objects as the original object, while a deep copy is a copy of an object that contains copies of the objects themselves. The shallow copy is created using the spread operator ..., while the deep copy is created using the JSON.stringify and JSON.parse methods or by manually recursively copying all properties of the original object.

Similar Posts

Leave a Reply

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