structuredClone
Creates a deep copy of an object with all nested data.
Available since: Web API
Syntax
structuredClone(value)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | any | The value to copy. |
Return value
anyA deep copy of the value.
Examples
Nested objects are copied too:
const original = { name: 'Anna', address: { city: 'Berlin' } };
const copy = structuredClone(original);
copy.address.city = 'Paris';
console.log(original.address.city);Output:
BerlinFor comparison — spread copies only the top level:
const original = { name: 'Anna', address: { city: 'Berlin' } };
const copy = { ...original };
copy.address.city = 'Paris';
console.log(original.address.city);Output:
ParisDates, Maps and Sets keep their type:
const data = { created: new Date(0), tags: new Set(['a']) };
const copy = structuredClone(data);
console.log(copy.created instanceof Date, copy.tags.has('a'));Output:
true trueNotes
Functions, DOM elements and class instances with methods cannot be cloned: functions throw a DataCloneError and class objects lose their methods. The old JSON.parse(JSON.stringify(obj)) trick also loses dates, undefined and Maps.
See also
- Object.assign — Copies properties from some objects into another.
- Spread syntax — Three dots spread an array or object into separate items.
- JSON.stringify — Converts a value to a JSON string.
Related recipes
In the tutorial
- Immutability — Mutable and immutable data in JavaScript: object references, copying with spread, the toSorted and with methods, Object.freeze and structuredClone.