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
.
Top comments (5)
Not really. Using the built in
structuredClone
is even easier, and works better:JSON.parse(JSON.stringify(object))
efficiently creates a copy of simple objects by converting them to aJSON
string and back, but loses complex data types likeNaN
,Set
andMap
.structuredClone
preserves complex data types and handlesNaN
andSet
, but doesn't supportfunctions
orsymbols
and may not be universally available.Let's take an example:
original
object containing various data such asundefined
,Infinity
,NaN
,Date
,RegExp
,ArrayBuffer
,Set
andMap
. Propertiesfunc
andsymbol
are commented.JSON.parse(JSON.stringify(object))
structuredClone
Case #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.