Absolute Modern Way to Deep Clone Object in JavaScript

Sai Kiran
3 min readJan 21, 2023

--

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

notification object

then using JSON.stringify() and JSON.parse() perform the deep copy. Following is the result:

json deep copy

let’s do same with structureClone() . Here is the log.

structured deep copy example

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

console example javascript

--

--

Sai Kiran

Web Developer | javascript | react | vue | blockchain enthusiast | Lunar enthusiast