Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

structuredClone

Creates a deep copy of an object with all nested data.

Available since: Web API

Syntax

structuredClone(value)

Parameters

ParameterTypeDescription
valueanyThe 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:

Berlin

For 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:

Paris

Dates, 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 true

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.