Deep Cloning: structuredClone vs JSON

Difficulty: Intermediate

Question

What are the different ways to clone objects in JavaScript (spread, Object.assign, JSON, structuredClone), and what are the limitations of each?

Answer

JavaScript has two kinds of copies: a shallow copy duplicates only the top-level properties, so nested objects are still shared, while a deep copy duplicates every level. Spread ({...obj}, [...arr]) and Object.assign make shallow copies. For deep copies, the modern built-in is structuredClone(value), available in all current browsers and Node.js 17+, which handles nested objects, Date, Map, Set and circular references; the older JSON.parse(JSON.stringify(obj)) trick works only for plain JSON-safe data.

Why shallow copies surprise people

const copy = { ...order } creates a new outer object, but copy.address === order.address is still true. Changing copy.address.city changes the original too. This is the bug behind many "state changed unexpectedly" issues in React and Redux, where you must create new objects at every level you modify.

Comparing the options

MethodDepthDatesMap / SetFunctionsundefinedCircular refsClass prototype
Spread / Object.assignShallowShared referenceShared referenceCopied as referenceKeptFine (shallow)Lost (plain object)
JSON.parse(JSON.stringify())DeepBecome stringsBecome {}DroppedDropped from objects, null in arraysThrows TypeErrorLost
structuredClone()DeepReal DateReal Map / SetThrows DataCloneErrorKeptSupportedLost
Lodash cloneDeepDeepReal DateReal Map / SetKept as reference in objectsKeptSupportedPreserved

More JSON pitfalls: NaN and Infinity become null, BigInt throws, and Symbol keys and values disappear.

What structuredClone can and cannot do

structuredClone uses the same structured clone algorithm the browser uses for postMessage, IndexedDB and Web Workers. It supports primitives (including BigInt), plain objects, arrays, Date, RegExp, Map, Set, ArrayBuffer, typed arrays, Blob, File, ImageData and most Error types, and it preserves shared and circular references.

It does not:

It also accepts a transfer option to move ArrayBuffers instead of copying them, which is how you hand large binary data to a worker cheaply.

Choosing in practice

Deep cloning large objects is not free. If you clone on every keystroke or render, consider whether you need a copy at all.

structuredClone vs spread vs JSON. Switch the copy method and add a method under Tweak to see where each breaks.
  1. Deep copy: structuredClone copies nested objects, so the copy's address is independent.
  2. Keeps rich types: Dates, Maps, Sets, typed arrays and cycles survive.
  3. Throws on functions: Objects with methods cause a DataCloneError.
  4. Spread is shallow: Nested objects stay shared.

Code examples

Shallow copy bug and the structuredClone fix

const order = {
  id: 'ord_77',
  address: { city: 'Bengaluru' },
  placedAt: new Date('2026-01-15T10:00:00Z'),
};

const shallow = { ...order };
shallow.address.city = 'Mumbai';
console.log(order.address.city); // original changed!

const deep = structuredClone(order);
deep.address.city = 'Pune';
console.log(order.address.city, deep.address.city);
console.log(deep.placedAt instanceof Date);

const node = { name: 'a' };
node.self = node;
const copy = structuredClone(node); // circular reference is fine
console.log(copy.self === copy);

Spread shares the nested address object, so mutating the copy leaks into the original. structuredClone duplicates every level, keeps Date as a Date and preserves the circular reference.

JSON and structuredClone limitations side by side

const data = {
  when: new Date(0),
  tags: new Set(['veg']),
  missing: undefined,
  ratio: NaN,
  greet() { return 'hi'; },
};

const viaJson = JSON.parse(JSON.stringify(data));
console.log(viaJson);

try {
  structuredClone(data);
} catch (e) {
  console.log(e.name); // functions cannot be cloned
}

class Money {
  constructor(paise) { this.paise = paise; }
  toRupees() { return this.paise / 100; }
}
const cloned = structuredClone(new Money(1500));
console.log(cloned instanceof Money, typeof cloned.toRupees);

JSON turns the Date into a string, the Set into an empty object, NaN into null, and drops undefined and the function. structuredClone refuses functions and returns class instances as plain objects without their methods.

Key points

Common follow-up questions

Interview tips

Concepts covered

Shallow Copy, Deep Clone, structuredClone, JSON.parse(JSON.stringify()), Structured Clone Algorithm

More JavaScript Interview questions