SnippetJavaScript

Deep-clone an object

The built-in structuredClone deep-copies nested objects and arrays with no library and no JSON round-trip, plus what it can't clone.

Last updated

Snippetjavascript
function deepClone(value) {
  return structuredClone(value);
}

const original = { a: 1, nested: { b: [1, 2, 3] } };
const copy = deepClone(original);
copy.nested.b.push(4);
// original.nested.b is untouched: [1, 2, 3]

How it works

structuredClone is a global function (Node 17+, all current browsers) built on the structured-clone algorithm the platform already uses for postMessage and IndexedDB — it walks the whole object graph and copies nested objects and arrays by value, so mutating the copy's nested.b array never touches the original's.

Before this existed, the common trick was JSON.parse(JSON.stringify(value)), which quietly drops or mangles anything JSON can't represent (undefined, functions, Dates become strings). structuredClone is both faster and more honest: it throws on what it can't handle instead of silently corrupting it.

Edge cases to know

  • Functions can't be cloned — structuredClone throws a DataCloneError if the object graph contains one, including class instances with methods on the prototype chain (plain data survives, but you lose the class identity).
  • DOM nodes, and a handful of other platform objects, aren't cloneable either — clone the data you extract from them, not the node itself.
  • It IS deep, unlike Object.assign or the spread operator, but it's a snapshot at call time: later mutations to the original never propagate to the copy, by design.

Related in Snippets