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, borutoCopyis a completely independent copy of boruto. Changes to borutoCopydo not affect boruto.
 



 
    
Top comments (5)
Not really. Using the built in
structuredCloneis even easier, and works better:JSON.parse(JSON.stringify(object))efficiently creates a copy of simple objects by converting them to aJSONstring and back, but loses complex data types likeNaN,SetandMap.structuredClonepreserves complex data types and handlesNaNandSet, but doesn't supportfunctionsorsymbolsand may not be universally available.Let's take an example:
originalobject containing various data such asundefined,Infinity,NaN,Date,RegExp,ArrayBuffer,SetandMap. Propertiesfuncandsymbolare commented.JSON.parse(JSON.stringify(object))structuredCloneCase #1
Case #2
@jahid6597
Thanks ๐ As I am still learning and was not aware about the structuredClone
@jonrandy
Thanks ๐
Thanks you. Wasn't aware about this fn.