What is structuredClone in JavaScript: Simple Explanation and Usage
structuredClone is a built-in JavaScript function that creates a deep copy of a given value, including objects, arrays, and more complex data types. It copies all nested data without keeping references to the original, unlike shallow copies.How It Works
Imagine you have a toy model made of many small parts glued together. If you want a new model exactly like it but separate, you need to copy every part, not just the outer shell. structuredClone works like that: it copies every piece inside an object or array, so the new copy is fully independent.
This function handles many data types, including objects, arrays, Maps, Sets, Dates, and even typed arrays. It does this by using a structured cloning algorithm that understands how to copy complex data safely without mixing the original and the copy.
Unlike simple copying methods that only copy the top layer (shallow copy), structuredClone goes deep inside nested structures, making sure changes to the copy do not affect the original.
Example
This example shows how structuredClone creates a deep copy of an object with nested properties. Changing the copy does not affect the original.
const original = { name: 'Alice', scores: [10, 20, 30], details: { age: 25, city: 'NY' } }; const copy = structuredClone(original); copy.name = 'Bob'; copy.scores.push(40); copy.details.city = 'LA'; console.log('Original:', original); console.log('Copy:', copy);
When to Use
Use structuredClone when you need a complete, independent copy of complex data like objects or arrays with nested parts. This is useful when you want to change the copy without affecting the original data.
Common real-world uses include:
- Copying state in web apps to avoid accidental changes.
- Duplicating data before editing or sending it somewhere else.
- Working with data structures that include Maps, Sets, or Dates.
It is safer and easier than manually copying each part or using JSON methods, which can lose some data types.
Key Points
- Deep copy: Copies all nested data, not just the top level.
- Supports many types: Works with objects, arrays, Maps, Sets, Dates, and more.
- Independent copy: Changes to the copy do not affect the original.
- Better than JSON: Preserves data types that JSON.stringify/parse cannot.
- Built-in: No need for extra libraries or complex code.