Deep Copy a JavaScript Object: structuredClone vs JSON vs Spread

Summary

For deep-copying plain data in modern JavaScript, prefer structuredClone(), which preserves Dates, Maps, Sets, undefined, NaN, circular references, and BigInt while failing loudly on functions or symbols, and use its transfer option for large ArrayBuffers when the source no longer needs ownership. Avoid the JSON.parse(JSON.stringify(obj)) shortcut for general cloning because it silently converts Dates to strings, turns Map and Set into empty objects, drops undefined properties, and changes NaN to null. Spread and Object.assign only create shallow copies, so nested objects remain shared and mutations leak back to the original. For class instances, structuredClone returns a plain object without methods or prototype, so add a clone() method that restores the prototype for public-field classes or manually reconstructs private state through the constructor.

To deep copy a JavaScript object, use structuredClone(obj). It's built into every current browser and into Node.js since v17, it copies nested objects, Dates, Maps, Sets and circular references correctly, and it throws a clear error when it meets something it can't copy. The old JSON.parse(JSON.stringify(obj)) trick silently changes your data, and spread ({ ...obj }) only copies the top level. The catch with structuredClone is class instances: you get a plain object back, without its methods. Here is what each approach does to the same object, and how to work around the cases structuredClone doesn't cover.

Spread and Object.assign are shallow

Spread syntax copies the object's own enumerable properties into a new object, but any property that holds an object still points at the same object. The MDN page on spread syntax puts it plainly: spread "effectively goes one level deep", and "the same is true with Object.assign() — no native operation in JavaScript does a deep clone." Array.prototype.slice(), concat() and Array.from() are shallow in the same way.

Here's the test object used for the rest of this article, and what spread does to it:

const original = {
  name: "report",
  tags: ["a", "b"],
  meta: { owner: { id: 7 } },
  created: new Date("2026-11-28T00:00:00Z"),
  lookup: new Map([["x", 1]]),
  seen: new Set([1, 2]),
  missing: undefined,
  ratio: NaN,
};

const spread = { ...original };
spread.meta.owner.id = 99;
console.log("spread shares nested objects:", original.meta.owner.id);
spread shares nested objects: 99

Changing the copy changed the original. That's the bug people usually hit first, often in React or Redux state updates where a nested object was "copied" with spread and then mutated.

What JSON.parse(JSON.stringify()) gets wrong

The JSON round trip does produce a fully separate object, which is why it became the standard trick. The problem is that JSON has fewer types than JavaScript, so anything that doesn't map to JSON gets converted or dropped. Running the same object through it in Node.js 23.9:

const viaJson = JSON.parse(JSON.stringify(original));
console.log("JSON:", viaJson);
console.log("JSON created is a", typeof viaJson.created);
JSON: {
  name: 'report',
  tags: [ 'a', 'b' ],
  meta: { owner: { id: 7 } },
  created: '2026-11-28T00:00:00.000Z',
  lookup: {},
  seen: {},
  ratio: null
}
JSON created is a string

Four things changed, and none of them raised an error. The Date became an ISO string, because Date implements toJSON(). The Map and the Set became empty objects. The missing key disappeared, and NaN turned into null. All of this is documented behaviour of JSON.stringify: undefined, functions and Symbols are omitted from objects (and become null in arrays), Infinity and NaN become null, and since only enumerable own properties are visited, "Map, Set, etc. will become "{}"".

The Date case is the one that bites in production. The copy looks right when you log it, then copy.created.getTime() throws a TypeError later, somewhere far from the clone. Two inputs make the JSON trick throw outright:

JSON circular: TypeError: Converting circular structure to JSON
    -- starting at object with constructor 'Object'
    --- property 'self' closes the circle
JSON bigint: TypeError: Do not know how to serialize a BigInt

structuredClone keeps the types

structuredClone() uses the structured clone algorithm, the same algorithm used to pass data to workers with postMessage() and to store objects in IndexedDB. It's defined in the WHATWG HTML standard rather than in ECMAScript, so it's a web platform API that Node.js also exposes as a global. The MDN reference lists it as available across browsers since March 2022.

const viaClone = structuredClone(original);
console.log("structuredClone:", viaClone);
console.log("clone created is a Date:", viaClone.created instanceof Date);
viaClone.meta.owner.id = 99;
console.log("original untouched:", original.meta.owner.id);
structuredClone: {
  name: 'report',
  tags: [ 'a', 'b' ],
  meta: { owner: { id: 7 } },
  created: 2026-11-28T00:00:00.000Z,
  lookup: Map(1) { 'x' => 1 },
  seen: Set(2) { 1, 2 },
  missing: undefined,
  ratio: NaN
}
clone created is a Date: true
original untouched: 7

Everything survived: a real Date, a real Map and Set, the undefined key and NaN. Circular references and BigInt work too. Clone an object whose self property points back at itself and the copy's self points at the copy (c.self === c is true), and { n: 10n } comes back as { n: 10n }. The supported types include Array, ArrayBuffer, Date, Map, Set, RegExp, typed arrays, the standard Error types, and web types such as Blob and File.

What structuredClone can't copy

The difference from JSON is that the unsupported cases mostly fail loudly. Functions and Symbol values throw a DataCloneError, and so do DOM nodes in a browser:

clone function: DataCloneError: onSave() {} could not be cloned.
clone symbol value: DataCloneError: Symbol(x) could not be cloned.

So an object with a method on it ({ onSave() {} }) can't be cloned at all, where JSON would have quietly returned {}. That's usually what you want. If the object has callbacks in it, it's probably not plain data, and a copy wouldn't behave the way you expect anyway.

A few things are lost without an error, and MDN lists them:

  • The prototype chain isn't copied, so class instances come back as plain objects.
  • Getters and setters aren't copied. A getter is called once and its result is stored as an ordinary writable property.
  • Class private fields (#field) aren't copied.
  • A RegExp's lastIndex is reset.
  • Symbol-keyed properties are skipped. In our run, Object.getOwnPropertySymbols(clone).length was 0.

The class instance case catches people most often:

class Point {
  constructor(x, y) { this.x = x; this.y = y; }
  length() { return Math.hypot(this.x, this.y); }
}
const pc = structuredClone(new Point(3, 4));
clone class instance: { x: 3, y: 4 }
instanceof Point: false
pc.length(): TypeError: pc.length is not a function

Cloning class instances

If the class keeps its state in ordinary public fields, clone the data and put the prototype back. A clone() method keeps that logic in one place:

class Point {
  constructor(x, y) { this.x = x; this.y = y; }
  length() { return Math.hypot(this.x, this.y); }
  clone() {
    return Object.setPrototypeOf(structuredClone(this), Point.prototype);
  }
}
const copy = new Point(3, 4).clone();
console.log(copy instanceof Point, copy.length());
true 5

This doesn't work for classes with private fields, because the fields never reach the copy. Calling a method that reads #balance on such a copy fails:

TypeError: Cannot read private member #balance from an object whose class did not declare it

For those classes, write the clone() method by hand and build the copy through the constructor, passing the private state in (return new Account(this.#balance), given a constructor that accepts a balance). Only the class knows which of its internals should be copied and which shared, and a generic deep copy can't make that call for it.

Moving large buffers with transfer

structuredClone takes a second argument, { transfer: [...] }, a list of transferable objects to move into the result instead of copying. For a big ArrayBuffer this skips the copy entirely, and the original is detached:

const bytes = new Uint8Array(16 * 1024 * 1024);
const moved = structuredClone(bytes, { transfer: [bytes.buffer] });
console.log("original byteLength:", bytes.byteLength);
console.log("moved byteLength:", moved.byteLength);
original byteLength: 0
moved byteLength: 16777216

Only use this when you're done with the source. After the transfer, the original view has a length of 0, and anything else holding that buffer sees an empty one.

Which one to use

Use spread when you only need a new top-level object, which is the common case for immutable state updates where you replace nested objects rather than mutate them. Use structuredClone for a real deep copy of data: API responses, config, state snapshots, anything with Dates or Maps in it. Keep JSON.parse(JSON.stringify()) for when you actually want JSON semantics, such as checking that a value survives being sent over the wire. MDN's own JSON page recommends structuredClone for deep copying instead. For class instances, give the class a clone() method rather than looking for a generic deep copy that handles everything, because none of the built-ins do.

JAVASCRIPT NODE.JS DEEP COPY JSON.STRINGIFY STRUCTUREDCLONE SPREAD SYNTAX

  RELATED

  COMMENTS

0

No comment for this article.