DEV Community

Dina Andrandraina
Dina Andrandraina

Posted on

Native deep clone in JS

I recently discovered a new feature in Javascript 🎉. I am a little bit late but I'm really excited about this feature.

Finally, there's a simpler way to deep clone a value using the new native function structuredClone available in recent version of NodeJS and JS engines.

As we know, for complex types, assignation will not copy the values but the reference.

const person = { name: 'John Doe' }
const anotherPerson = person

person.name = 'Smith'

console.log(person.name) // Smith
console.log(anotherPerson.name) // Smith
Enter fullscreen mode Exit fullscreen mode

person and anotherPerson contain both the reference of the same object, so if mutate this object, both of them will see the changes.

Sometime, we don't need this behavior but we want to have an independant value, so we need to deep clone it.

Before, to deep clone a complex value like Object or Arrays, we have to do some hacks like
JSON.parse(JSON.stringify(val)), some of us may have used libraries, or created a helper to do the stuff.

Now it can be done by using a single native function structuredClone.

I tried it, I like it and I hope you'll like it too.

👉 https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

Peace ✌

Top comments (0)