Shallow Copy vs Deep Copy in JavaScript
Raju Saha
Posted on June 24, 2024
When working with objects in JavaScript, understanding the difference between shallow copy and deep copy is crucial. This knowledge helps avoid unexpected behavior, especially when dealing with nested objects.
Shallow Copy
A shallow copy duplicates the top level of an object but does not recursively copy nested objects. Instead, it retains references to the original nested objects. Here are some common methods for creating shallow copies: Object.assign()
and the spread operator {...object}
.
Example
In this example, changing the fullName
in narutoCopy does not affect the original naruto object.
However, with nested objects, a shallow copy only copies the references:
In this case, both narutoDetails and narutoDetailsCopy have the same reference to the parent's object. Changing the father property in narutoDetailsCopy
also changes it in narutoDetails
.
Deep Copy
A deep copy duplicates an object along with all the objects it references, recursively. The easiest way to achieve this in JavaScript is by using JSON.parse(JSON.stringify(object))
. For more complex scenarios, libraries like lodash provide deep copy functions.
Example
In this example, borutoCopy
is a completely independent copy of boruto
. Changes to borutoCopy
do not affect boruto
.
Posted on June 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.