Shallow Copy vs Deep Copy in JavaScript

rajusaha

Raju Saha

Posted on June 24, 2024

Shallow Copy vs Deep Copy in JavaScript

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

Code snippet of the shallow copy
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:

Nested Shallow Copy Code Snippet

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

Deep Copy Code Snippet

In this example, borutoCopyis a completely independent copy of boruto. Changes to borutoCopydo not affect boruto.

💖 💪 🙅 🚩
rajusaha
Raju Saha

Posted on June 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related