Basically, clone means making a copy. In Javascript, clone means also making a copy but there are two types of clone in Javascript. One is a Shallow clone and the second is a Deep clone. To understand this shallow and deep clone we will consider one object like this:
1) Shallow clone: Shallow clone is a clone in which changes to the original object (here person) are reflected in the clone object also. To understand this create a clone of a person like this:
See the Pen Untitled by Bibek Kumar Bhagat (@Bibek-Kumar-Bhagat) on CodePen.
Here newPerson is the exact copy of the person and the change to person name is reflected in the newPerson name. So newPerson is called the Shallow clone of the person.
2) Deep Clone: Deep clone is a clone in which changes to the original object(here person) are not reflected in the clone object. For Example:
See the Pen Untitled by Bibek Kumar Bhagat (@Bibek-Kumar-Bhagat) on CodePen.
Here change to person name is not reflected to newPerson name. So this is called Deep clone of the person in javascript. There are three ways to make a Deep clone in javascript. First is using Spread Operator (...) which applies in the above example. The second is using Object.assign() and the third is using JSON.parse() with JSON.stringify().
Deep Clone using Objec.assign():
See the Pen Untitled by Bibek Kumar Bhagat (@Bibek-Kumar-Bhagat) on CodePen.
Deep Clone using JSON.parse() with JSON.stringify():
See the Pen Untitled by Bibek Kumar Bhagat (@Bibek-Kumar-Bhagat) on CodePen.
0 Comments
Thank you for Comment