DEV Community

MR.H
MR.H

Posted on • Edited on

6 2 1 1 2

Javascript structuredClone

The structuredClone method allows you to deep clone a object including its keys and values.

const person = {
    name: 'Paul G. Reynolds',
    skills: ['javascript','react','ember','vue']
    dob: new Date('1995-11-25')
}

const person2 = structuredClone(person);
person2.name = 'Brad T. Kennedy';

console.log(person.name); //Paul G. Reynolds
console.log(person2.name); //Brad T. Kennedy
Enter fullscreen mode Exit fullscreen mode

As you see in the above code altering person2.name did not alter person.name.

You might think we can achieve this by using javascript spread operator.

const person2 = {
   ...person
}
Enter fullscreen mode Exit fullscreen mode

But, the problem is skills is an array altering person2.skills will alter person.skills too.

In such case you can think we can also use,

person2 = JSON.parse(JSON.stringify(person))
//{"name":"Paul G. Reynolds","skills":["javascript","react","ember","vue"],"dob":"1995-11-25T00:00:00.000Z"}
Enter fullscreen mode Exit fullscreen mode

Here the problem is dob is a Date object it will loose it's properties and become string value.

Previously we need to use lot of workarounds like this to achieve deep cloning now we have a built in method structuredClone.

One thing to keep in mind when using structuredClone is, that it only works on structured objects. If you try to clone an unstructured object, you will get an error. For example:

const func = () => {
  console.log('Hello, world!');
};

const func2 = structuredClone(func); // Error!
Enter fullscreen mode Exit fullscreen mode

In this example, we tried to clone a function object using structuredClone method, but it will raise an error because functions are not structured objects.

Supported browsers

Chrome Edge Firefox Safari
98 98 94 15.4

Source: MDN

Conclusion

The structuredClone method in JavaScript is a powerful tool for making exact copies of objects.


If you read until the end leave a like and share your thoughts in the comment section

Happy coding

Checkout full spec: MDN StructuredClone

Names generated from https://www.fakenamegenerator.com/

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Pieces AI Productivity Summit

​Join top AI leaders, devs, & enthusiasts for expert talks, live demos, and panels on how AI is reshaping developer productivity at the Pieces AI Productivity Summit.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️