StructuredClone in JavaScript - Deep Cloning Made Easy
structuredClone
is a JavaScript function that makes deep cloning easy!
Often, developers reach for something like JSON.parse(JSON.stringify(ObjToClone));
.
But, I think you'll agree this function looks more intuitive.
Why Use structuredClone?
A simple copy might still link to the original when you copy complex things like objects. Changes in the copy can affect the original. structuredClone
prevents this.
It creates a totally separate copy.
How to Use structuredClone
Here's how you use structuredClone
:
Have Something to Copy: You need an object or something similar to copy. Example:
const myObject = { name: "Alice", age: 30 };
Use structuredClone: Use
structuredClone
to make a copy. Example:const copiedObject = structuredClone(myObject);
Now You Have a Copy:
copiedObject
is a complete, separate copy ofmyObject
. Changes tocopiedObject
won't affectmyObject
.
Example
It's usually easier to understand when you see it in action:
Copying an Object
const original = { name: 'Bob', age: 25 }; const clone = structuredClone(original); console.log(clone); // { name: 'Bob', age: 25 }
Notes
- Deep Copy: It copies everything inside the object, including nested objects.
- No Links to Original: The copy is totally separate from the original.
- Handles Complex Data: It works with arrays, objects, maps, sets, dates, and more.
- Safe and Easy: It's a safe and easy way to copy complex data in JavaScript.
That's it! You can now use structuredClone
to copy objects and more in JavaScript.