Sub topic 12
JSON Round-Trip Cloning Versus structuredClone
This chapter assumes you already know what JSON.stringify and JSON.parse do with ordinary values. You should also know how they treat undefined, functions, symbols, NaN, Dates, cycles, and BigInt, because all of that comes back here. You should be comfortable with object references in JavaScript and with try/catch. The code runs in Node.js 17 or later and in any current browser, where structuredClone is a global function.
Why Copying Objects Is Harder Than It Looks
Assigning an object to a new variable does not copy it. Both variables point to the same object, so a change through one shows up through the other. The spread operator ({ ...obj }) and Object.assign make a shallow copy: they create a new top-level object, but nested objects and arrays are still shared.
const settings = { theme: "dark", layout: { columns: 3 } };
const alias = settings;
const shallow = { ...settings };
shallow.theme = "light";
shallow.layout.columns = 1;
console.log(settings.theme); // "dark" (top level was copied)
console.log(settings.layout.columns); // 1 (nested object is shared)
console.log(alias === settings); // trueA deep copy duplicates every nested object, so the copy and the original share nothing that can change. For years the common shortcut for a deep copy was JSON.parse(JSON.stringify(value)). It works because stringify walks the whole structure and parse builds brand-new objects from text. The catch is that the copy can only hold what JSON can represent, and as earlier chapters showed, that is a small set of types.
The JSON Round Trip as a Clone
function jsonClone(value) {
return JSON.parse(JSON.stringify(value));
}
const order = { id: 42, items: [{ sku: "A1", qty: 2 }], paid: true };
const copy = jsonClone(order);
copy.items[0].qty = 99;
console.log(order.items[0].qty); // 2 (fully independent)When the data is plain objects, arrays, strings, finite numbers, booleans, and null, this clone is correct. The trouble starts when the data contains anything else. The round trip never throws on most of those values. It just changes or drops them, and the bug shows up later, far from the clone.
What the round trip changes
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const original = {
when: new Date(0),
tags: new Set(["a", "b"]),
lookup: new Map([["k", 1]]),
pattern: /ab+c/i,
bytes: new Uint8Array([1, 2]),
missing: undefined,
ratio: NaN,
big: Infinity,
negZero: -0,
err: new Error("boom"),
point: new Point(3, 4)
};
const viaJson = JSON.parse(JSON.stringify(original));
console.log(viaJson);
// {
// when: '1970-01-01T00:00:00.000Z',
// tags: {},
// lookup: {},
// pattern: {},
// bytes: { '0': 1, '1': 2 },
// ratio: null,
// big: null,
// negZero: 0,
// err: {},
// point: { x: 3, y: 4 }
// }
console.log("missing" in viaJson); // false
console.log(viaJson.point instanceof Point); // falseEach line here comes from a rule covered earlier:
- The Date becomes an ISO string through its built-in
toJSON. Set,Map, andRegExphave no enumerable own properties, so they become{}.- A typed array becomes an object with numeric string keys.
- The
undefinedproperty disappears. NaNandInfinitybecomenull, and-0becomes0.- An
Errorbecomes{}becausemessageandstackare not enumerable. - The
Pointinstance keeps its data but loses its prototype, solength()is gone.
What the round trip breaks
Two kinds of structure fail outright or quietly lose their meaning.
const shared = { n: 1 };
const graph = { a: shared, b: shared };
const copy = JSON.parse(JSON.stringify(graph));
console.log(copy.a === copy.b); // false (one object became two)
const loop = { name: "loop" };
loop.self = loop;
try {
JSON.parse(JSON.stringify(loop));
} catch (err) {
console.log(err.name); // "TypeError" (cyclic structure)
}
try {
JSON.parse(JSON.stringify({ count: 10n }));
} catch (err) {
console.log(err.name); // "TypeError" (BigInt cannot be serialized)
}Shared references are duplicated. If your code relies on copy.a and copy.b being the same object, for example a cache or a normalized store, the copy now behaves differently from the original. Cycles and BigInt throw a TypeError. The circular replacer from the earlier chapter avoids the throw, but it writes a "[Circular]" marker instead of a real loop, so the output is no longer a faithful clone.
structuredClone: A Real Deep Copy
structuredClone(value) uses the structured clone algorithm, the same mechanism browsers use to send data to Web Workers with postMessage and to store it in IndexedDB. It copies values directly in memory, with no text step in between, and it knows about many built-in types.
const original = {
when: new Date(0),
tags: new Set(["a", "b"]),
lookup: new Map([["k", 1]]),
pattern: /ab+c/i,
bytes: new Uint8Array([1, 2]),
missing: undefined,
ratio: NaN,
negZero: -0,
count: 10n,
err: new Error("boom")
};
original.self = original;
const clone = structuredClone(original);
console.log(clone.when instanceof Date); // true
console.log(clone.tags.has("b")); // true
console.log(clone.lookup.get("k")); // 1
console.log(clone.pattern.test("ABBC")); // true
console.log(clone.bytes instanceof Uint8Array); // true
console.log("missing" in clone); // true
console.log(Number.isNaN(clone.ratio)); // true
console.log(Object.is(clone.negZero, -0)); // true
console.log(clone.count); // 10n
console.log(clone.err.message); // "boom"
console.log(clone.self === clone); // true (cycle preserved)
console.log(clone.when === original.when); // false (still a new object)Shared references are preserved too. If two properties point to the same object in the original, they point to the same new object in the clone.
Where structuredClone stops
structuredClone is not a universal copier. It has hard limits, and unlike the JSON round trip it throws on most of them instead of failing quietly.
try {
structuredClone({ handler: () => 1 });
} catch (err) {
console.log(err.name); // "DataCloneError"
}
try {
structuredClone({ id: Symbol("x") });
} catch (err) {
console.log(err.name); // "DataCloneError"
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const p = structuredClone(new Point(3, 4));
console.log(p); // { x: 3, y: 4 }
console.log(p instanceof Point); // false
const withSymbolKey = { [Symbol("hidden")]: 1, visible: 2 };
console.log(structuredClone(withSymbolKey)); // { visible: 2 }The error is a DOMException whose name is "DataCloneError". Functions, symbol values, DOM nodes, and some host objects such as sockets cannot be cloned. Class instances become plain objects: their own enumerable data comes through, but the prototype, methods, and private #fields do not. Symbol-keyed properties are skipped without an error. Getters are read once, and the clone stores the result as a plain data property.
Side-by-Side Comparison
| Value in the original | JSON round trip | structuredClone |
|---|---|---|
| Plain objects, arrays, strings, booleans, null | Copied | Copied |
| Finite numbers | Copied | Copied |
| `NaN`, `Infinity`, `-Infinity` | Become `null` | Preserved |
| `-0` | Becomes `0` | Preserved |
| `undefined` property | Dropped | Preserved |
| `Date` | Becomes ISO string | Preserved as `Date` |
| `Map`, `Set` | Become `{}` | Preserved |
| `RegExp` | Becomes `{}` | Preserved |
| Typed arrays, `ArrayBuffer` | Become index-keyed objects | Preserved |
| `Error` | Becomes `{}` | Preserved with `message` |
| `BigInt` | Throws `TypeError` | Preserved |
| Shared references | Duplicated | Preserved |
| Circular references | Throws `TypeError` | Preserved |
| Functions | Dropped, or `null` in arrays | Throws `DataCloneError` |
| Symbol values | Dropped, or `null` in arrays | Throws `DataCloneError` |
| Class instances | Plain object, prototype lost | Plain object, prototype lost |
| Objects with `toJSON` | Replaced by `toJSON` result | `toJSON` ignored |
The last row matters if your types use toJSON to control their serialized shape. The JSON clone gives you the serialized shape, not the original object. structuredClone ignores toJSON and copies the object's own properties.
When the JSON Round Trip Is Still the Right Choice
The JSON clone has one real strength: its output is exactly what would survive a trip over the network or into storage. That is sometimes what you want.
- Testing serialization. If an object is about to be saved to
localStorageor sent in a request body,JSON.parse(JSON.stringify(x))shows you precisely what the other side will receive. A Date that turns into a string here will be a string there too. - Normalizing to plain data. Sometimes you want Dates as strings,
toJSONapplied, andundefinedfields removed, for example before comparing two payloads or writing a snapshot test. - Combining with a replacer or reviver. The round trip lets you filter or transform data during the copy, which
structuredClonecannot do.
For a plain in-memory deep copy, prefer structuredClone. It handles more types, keeps cycles and shared references, and fails loudly instead of silently corrupting data.
Performance and Practical Notes
Speed depends on the engine, the shape of the data, and the size. On some engines and inputs the JSON round trip is faster for small, flat, string-heavy objects, and on others structuredClone wins. If cloning is on a hot path, measure with your real data instead of relying on general claims. In most applications the correctness difference matters more than the speed difference.
A few other details are worth knowing:
structuredCloneaccepts an options object with atransferlist. Transferring anArrayBuffermoves its memory into the clone and leaves the original detached with a byte length of 0. This is useful for large binary data and dangerous if other code still reads the original buffer.- Both approaches copy only own enumerable string-keyed properties of plain objects. Non-enumerable properties are skipped by both.
- If you must support very old runtimes without
structuredClone, a library such as Lodash'scloneDeepis a common fallback. Check its documentation for the types it supports.
Exercise
A config object is { retries: 3, timeout: undefined, startedAt: new Date(0), hosts: new Set(["a"]) }. What do JSON.parse(JSON.stringify(config)) and structuredClone(config) each return?
Show answer
The JSON round trip returns { retries: 3, startedAt: "1970-01-01T00:00:00.000Z", hosts: {} }. The timeout key is removed, the Date becomes a string, and the Set becomes an empty object. structuredClone returns an object with retries: 3, a timeout key holding undefined, a real Date for startedAt, and a Set containing "a".
Exercise
You clone const state = { user: u, selected: u }, where u is a single object. After cloning you set copy.user.name = "Bo". What is copy.selected.name with each method, and why?
Show answer
With the JSON round trip, copy.selected.name keeps its old value, because stringify writes u twice and parse builds two separate objects. With structuredClone, copy.selected.name is "Bo", because the algorithm tracks objects it has already copied, so both properties point to the same new object.
Exercise
structuredClone({ onSave() {} }) throws, but JSON.parse(JSON.stringify({ onSave() {} })) returns {}. Which behavior is safer for catching bugs, and how would you clone an object that holds callbacks?
Show answer
The throw is safer, because it reports at once that the data cannot be copied faithfully, while the JSON version quietly drops the method. To clone an object with callbacks, copy the data with structuredClone after separating out the functions, then reattach them, since functions are usually meant to be shared rather than duplicated. A dedicated clone() method on the owning class can also do this.