Niall Maher1 min read

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:

  1. Have Something to Copy: You need an object or something similar to copy. Example: const myObject = { name: "Alice", age: 30 };

  2. Use structuredClone: Use structuredClone to make a copy. Example: const copiedObject = structuredClone(myObject);

  3. Now You Have a Copy: copiedObject is a complete, separate copy of myObject. Changes to copiedObject won't affect myObject.

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.

JavaScriptJS

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Loading discussion...

Hey! 👋

Got something to say?

or to leave a comment.