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.
=
operator makes a reference to the same memory location and does not actually copy. Let's understand it with the example-
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(...)
Here when c
is modified,a
remains the same so c
is a copy of a
.
2.using Object.assign() method
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-
Applying one of the methods of shallow copy-
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-
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
andShallow Copy
in javascript.
Top comments (0)