In almost all the interview you will be asked “What is Shallow Copy and Deep Copy of objects in javascript? and how can we achieve them”
Most of you including me answered in the following way:
Spread operator, Object.assign()
and Object.create()
for the Shallow Copy.
Obviously, JSON.stringify()
for the deep copy.
But, now, there is a native way in the javascript to create a deep copy of objects.
structuredClone
is new function that is built into the javascript runtime to create deep copy of the objects.
Now, JSON.stringify()
is already in use but why is there need to introduce a totally new funtion for the same operation?
Answer is both does not behave in the same way. Let’s look at one example then we will understand why structuredClone
is suits better than JSON.stringify()
Let’s create a dummy notification object as follows
then using JSON.stringify()
and JSON.parse()
perform the deep copy. Following is the result:
let’s do same with structureClone()
. Here is the log.
If you closely observe, date should be a Date object not a string but incase of structuredDeepCopy, date is Date object NOT a string. JSON.stringify()
can not handle every type that we use in javascript.
There are lot other things that JSON.stringify()
can not handle in the javascript. So, it is better to go with the structuredClone()
.
oh wait! the real question is structuredClone()
can perform deep clone?
Here is the example
Thank you for reading. I provide high quality articles with no BS. If you like it clap and subscribe for the letters.
If you are preparing for the javascript and it’s framework interviews, I have written articles on the questions ( react.js , vue.js , HTML and CSS )that I was asked during my interviews.
Following are the links: