Sub topic 12
JSON Round-Trip Cloning Versus structuredClone
This chapter assumes you know how JSON.stringify handles unsupported values, how JSON.parse builds new objects, and why circular references make stringify throw. It compares two ways to deep-clone data: the classic JSON.parse(JSON.stringify(x)) round trip and the built-in structuredClone.
Why People Clone Through JSON
A deep clone copies an object and every object nested inside it, so changes to the copy never affect the original. For years JavaScript had no built-in way to do this, so developers chained the two JSON methods:
const settings = { theme: "dark", layout: { columns: 3 } };
const copy = JSON.parse(JSON.stringify(settings));
copy.layout.columns = 1;
console.log(settings.layout.columns); // 3This works because JSON.parse always builds new objects. It only works cleanly when the data already fits JSON's model of strings, finite numbers, booleans, null, plain objects, and arrays.
What the Round Trip Loses
Everything covered in earlier chapters applies here, because the clone is only as faithful as the JSON text in the middle. Dates become strings, Maps and Sets become {}, undefined properties disappear, NaN becomes null, and any toJSON method rewrites the value before it is copied.
const original = { when: new Date(0), tags: new Map([["a", 1]]) };
const viaJson = JSON.parse(JSON.stringify(original));
console.log(typeof viaJson.when); // "string"
console.log(viaJson.tags); // {}
const viaClone = structuredClone(original);
console.log(viaClone.when instanceof Date); // true
console.log(viaClone.tags.get("a")); // 1Two more problems are easy to miss. The round trip throws on cycles and on BigInt values. It also splits shared references: if two properties point to the same object, the copy gets two separate objects.
How structuredClone Works
structuredClone uses the structured clone algorithm, the same one browsers use for postMessage and IndexedDB. It copies values directly and never turns them into text. It is available in all modern browsers and in Node.js 17 and later.
const shared = { n: 1 };
const graph = { left: shared, right: shared, big: 10n, ratio: NaN };
graph.self = graph;
const copy = structuredClone(graph);
console.log(copy.self === copy); // true (cycle preserved)
console.log(copy.left === copy.right); // true (sharing preserved)
console.log(copy.left === shared); // false (still a deep copy)
console.log(copy.big, copy.ratio); // 10n NaNIts Limits
structuredClone is not a perfect copy either. It throws a DataCloneError on functions, symbols, and DOM nodes. It also drops prototypes, so class instances come back as plain objects without their methods.
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 instanceof Point); // false
console.log(p.x); // 3
try {
structuredClone({ fn: () => 1 });
} catch (err) {
console.log(err.name); // "DataCloneError"
}Getters are run during the copy and their results are stored as plain data properties. Other property descriptors, such as non-writable flags, are not copied.
Side-by-Side Comparison
| Input | JSON round trip | structuredClone |
|---|---|---|
| Date | ISO string | Date |
| Map, Set | `{}` | Map, Set |
| `undefined` property | dropped | kept |
| `NaN`, `Infinity` | `null` | kept |
| BigInt | throws TypeError | kept |
| Circular reference | throws TypeError | kept |
| Shared reference | duplicated | kept shared |
| Function | dropped silently | throws DataCloneError |
| Class instance | plain object, `toJSON` applied | plain object |
When the JSON Round Trip Still Makes Sense
Use JSON when you need the text anyway, for example when saving to localStorage or sending data over the network. Serializing also confirms the data will survive storage. For in-memory copies, structuredClone is the better default. The JSON round trip fails silently on data it cannot represent, while structuredClone throws, so you find out about the problem right away.
Exercise
An object holds { created: new Date(), visits: new Set([1, 2]), onSave: () => {} }. What does a JSON round trip produce, and what does structuredClone do with it?
Show answer
The JSON round trip gives { created: "<ISO string>", visits: {} } and silently drops onSave. structuredClone throws a DataCloneError because of the function. Remove or strip onSave first, and structuredClone will keep created as a Date and visits as a Set.
Exercise
Two properties a and b reference the same object. After cloning, you set copy.a.x = 5. What is copy.b.x with each approach?
Show answer
With the JSON round trip, copy.b.x is unchanged, because a and b became separate objects. With structuredClone, copy.b.x is 5, because the shared reference is preserved.