All questions

structuredClone

Premium

structuredClone

structuredClone makes a deep copy of a value — one that shares no references with the original — and, unlike the JSON.parse(JSON.stringify(...)) trick, it handles the types that JSON can't: Map, Set, Date, RegExp, typed arrays, and even circular references. It's the correct way to snapshot rich state.

Implement structuredClone(value). Recursively copy plain objects and arrays, clone the supported built-ins faithfully, and use a WeakMap to handle cycles and shared references so an already-cloned node is reused rather than copied twice (or looped forever).

Signature

function structuredClone(value) {
  // returns a deep copy sharing no references with `value`.
}

Examples

const src = { when: new Date(0), tags: new Set(['a']), nested: { n: 1 } };
const out = structuredClone(src);
out.nested.n = 2;      // src.nested.n stays 1
out.when instanceof Date; // true — a real Date, not a string
const a = { name: 'a' };
a.self = a;                 // circular
const clone = structuredClone(a);
clone.self === clone;       // true — the cycle is rebuilt within the clone

Notes

  • Deep — nested objects and arrays are recursively copied; the clone shares no references with the original.
  • Built-ins — clone Date (same time), RegExp (same source + flags), Map/Set (deeply), and typed arrays.
  • Cycles — a self- or mutually-referential structure must clone without infinite recursion; the clone's cycle points within the clone.
  • Shared references — if two places point at the same object, the clone must too (one clone, referenced twice — not two copies).
  • Primitives — numbers, strings, booleans, null, undefined (and functions) are returned as-is.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium