Hello Everyone,
In this post we will explore the difference between shallow and deep cloning and we will see what are some pitfalls with shallow cloning.
Before moving on, you should check out my last post on copy by value vs copy by reference, it will set you up to understand this one.
The shallow clone
A shallow clone means that certain (sub)-values are still connected to the original variable (references to the same point in memory).
For instance:
1let me = {2 name: "Swastik",3 age: 22,4 gender: "Male",5 address: {6 house: 325,7 street: 14,8 city: "NewDelhi",9 }10}1112let myShallowClone = {...me};1314console.log(me.name, myShallowClone.name, me.address.city, myShallowClone.address.city);15// Swastik, Swastik, NewDelhi, NewDelhi1617me.name = "Yadav";18me.address.city = "Bihar";1920console.log(me.name, myShallowClone.name, me.address.city, myShallowClone.address.city);21// Yadav Swastik Bihar Bihar
The pitfall with shallow copy
- The change in
me.name
does not affect themyShallowCopy.name
. - But the change in
me.address.city
also changesmyShallowCopy.address.city
because nested objects are only pointers / references.
The deep clone
A deep clone means that all values of new variable are copied and disconnected from the original variable. Changing me.address.city
should not affect myShallowCopy.address.city
.
One way to deep clone nested object is to manually copying all nested objects.
For instance:
1let me = {2 name: "Swastik",3 age: 22,4 gender: "Male",5 address: {6 house: 325,7 street: 14,8 city: "NewDelhi",9 }10}1112let myManualDeepClone = {...me, address: {...me.address}};1314me.address.city = "Bihar";1516console.log(me.address.city, myManualDeepClone.address.city);17// Bihar, NewDelhi
But what if you don’t want to copy all your nested objects manually? We can simply stringify our object and parse it right after.
For instance:
1let me = {2 name: "Swastik",3 age: 22,4 gender: "Male",5 address: {6 house: 325,7 street: 14,8 city: "NewDelhi",9 }10}1112let myDeepClone = JSON.parse(JSON.stringify(me));1314me.address.city = "Bihar";1516console.log(me.address.city, myDeepClone.address.city);17// Bihar, NewDelhi
Note: There is no pitfalls with cloning primitive datatypes, because they are by default refers to different points in memory.
So, I hope that now the difference between shallow and deep cloning is clear. if you found this post helpful, please do share and subscribe to my newsletter below or here.
Thank You!