# Deep Cloning: structuredClone vs JSON

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone
Last updated: 2026-11-28

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

| Method | Depth | Dates | Map / Set | Functions | undefined | Circular refs | Class prototype |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Spread / `Object.assign` | Shallow | Shared reference | Shared reference | Copied as reference | Kept | Fine (shallow) | Lost (plain object) |
| `JSON.parse(JSON.stringify())` | Deep | Become strings | Become `{}` | Dropped | Dropped from objects, `null` in arrays | Throws `TypeError` | Lost |
| `structuredClone()` | Deep | Real `Date` | Real `Map` / `Set` | Throws `DataCloneError` | Kept | Supported | Lost |
| Lodash `cloneDeep` | Deep | Real `Date` | Real `Map` / `Set` | Kept as reference in objects | Kept | Supported | Preserved |

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:

- clone functions or DOM nodes (throws `DataCloneError`)
- keep the prototype chain: a `class Order` instance comes back as a plain object without methods
- copy getters and setters (it copies the current value), property descriptors, or symbol-keyed properties

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

### Choosing in practice

- Updating React or Redux state: shallow copies at each changed level (`{...state, user: {...state.user, name}}`) or Immer. A deep clone of the whole state defeats memoization.
- Snapshotting plain data (form drafts, API payloads, undo history): `structuredClone`.
- Sending data over the network or to `localStorage`: you need JSON anyway, so JSON round-tripping is fine if you know its limits.
- Cloning class instances with behaviour: write a `clone()` method or copy constructor.

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

- Spread and Object.assign are shallow: nested objects stay shared.
- structuredClone is the built-in deep clone (browsers and Node.js 17+) and supports Date, Map, Set, typed arrays and circular references.
- structuredClone throws on functions and DOM nodes and does not keep prototypes, getters or symbol keys.
- JSON round-tripping loses Dates, Maps, Sets, undefined, functions, NaN and throws on BigInt and cycles.
- For immutable state updates, copy only the path you change rather than deep cloning everything.

## Common follow-up questions

- Write your own deep clone function that handles circular references.
- Why does structuredClone not preserve class instances?
- How does Immer avoid deep cloning the whole state tree?
- What is the transfer option of structuredClone used for?

## Interview tips

- Start by distinguishing shallow and deep copies with a nested object example; it frames the whole answer.
- Mention structuredClone by name; many candidates still only know the JSON trick.
- List concrete JSON failure cases (Date, undefined, cycles) rather than saying it "has issues".

## Concepts covered

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

Previous: [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors) · Next: [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Memory Leaks in JavaScript](https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks)
- [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types)
- [WebSockets and Real-time Communication](https://www.internhack.in/learn/interview/javascript-interview/js-websockets)
- [Advanced Regular Expressions](https://www.internhack.in/learn/interview/javascript-interview/js-regex-advanced)
- [JavaScript Performance Optimization](https://www.internhack.in/learn/interview/javascript-interview/js-performance-optimization)
- [Tagged Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-tagged-templates)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
