DEV Community

Cover image for Shallow Copy vs Deep Copy in JAVASCRIPT
Aman Sethi
Aman Sethi

Posted on

Shallow Copy vs Deep Copy in JAVASCRIPT

Shallow copy and deep copy are used to copy objects in javascript. Before directly jumping into the differences first let's see why objects are not copied using = operator.

Alt Text

= operator makes a reference to the same memory location and does not actually copy. Let's understand it with the example-

Alt Text

Thus it is clear from the example that a and b are both references to same memory location.So we cannot copy using = operator.

Shallow Copy

It is used to copy objects which are not nested(i.e. do not contain another object within them). There are two methods -

1.using spread(...)

Alt Text

Here when c is modified,a remains the same so c is a copy of a.

2.using Object.assign() method

Alt Text

Here when d is modified, a remains the same so d is a copy of a.

Deep Copy

Deep copy copies the objects irrespective of whether it is nested or not.It uses JSON.stringify() and JSON.parse() methods.Let's understand it with an example that has nested objects-

Alt Text

Applying one of the methods of shallow copy-

Alt Text

Observe that when the nested object of b is modified a also gets modified. The reason behind this is shallow copy in case of nested objects use the reference of nested objects and only make copy the parent object.

Applying JSON.stringify() and JSON.parse() methods for deep copy-

Alt Text

Here when the nested object of c is modified a remains the same.

I hope this blog helped you understand the differences between Deep Copy and Shallow Copy in javascript.

Top comments (0)