JavaScript Structured Clone: Copy Graphs Safely
Quick answer
structuredClone is a host-provided API that copies supported structured data, including cycles and some types that JSON cannot preserve.
How it works
Call structuredClone(value) for supported data such as arrays, ordinary records, Date, Map and Set. Repeated references and cycles within the cloned graph are retained, but clone identities differ from originals. Functions and certain host objects are not cloneable. Custom prototypes, accessors and descriptors are not generally preserved. A transfer list can move transferable resources such as ArrayBuffer rather than copying; this may detach the source. It is not part of core ECMA-262.
const a={};a.self=a; const b=structuredClone(a); console.log(b!==a,b.self===b);Expected output in Node.js:
true trueThe clone has its own identity and retains its cycle.
const m=new Map([["a",{n:2}]]); const c=structuredClone(m); c.get("a").n=5; console.log(c instanceof Map,m.get("a").n,c.get("a").n);Expected output in Node.js:
true 2 5Map type and independent nested data survive cloning.
Common mistakes
Do not equate cloning with sanitizing untrusted data or preserving every class invariant. Check the host and supported types.
Practice
Clone a nested data record and change a copied field. Explain why the original remains unchanged and why a shallow copy would differ.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Structured Clone: Copy Graphs Safely — Knowledge Check
Apply the taught concept and predict the output.
Which of these is a supported structured-clone data type in the tested host?
What is the effect of transferring an ArrayBuffer through structuredClone in a supporting host?
Does structuredClone generally preserve arbitrary custom property descriptors?
What is the exact console output in JavaScript Structured Clone: Copy Graphs Safely example 1?
const a={};a.self=a; const b=structuredClone(a); console.log(b!==a,b.self===b);What is the exact console output in JavaScript Structured Clone: Copy Graphs Safely example 2?
const m=new Map([["a",{n:2}]]); const c=structuredClone(m); c.get("a").n=5; console.log(c instanceof Map,m.get("a").n,c.get("a").n);