structuredClone vs JSON Parse/Stringify
You'll learn why structuredClone is a more robust deep cloning solution than the common JSON.parse(JSON.stringify()) trick.
The JSON Round-Trip Limitation
For years, developers used JSON.parse(JSON.stringify(obj)) as a quick deep cloning hack. While clever, it has serious limitations:
What JSON loses:
- Functions — completely stripped out
- undefined values — removed from objects, converted to
nullin arrays - Dates — converted to strings
- RegExp, Map, Set — become empty objects or are lost
- Circular references — throw errors immediately
Think of JSON like copying a document by taking a photo: anything that can't be captured in a flat image (like texture or smell) is lost forever.
How structuredClone Excels
structuredClone uses the browser's structured clone algorithm, which was designed for sending data between workers and contexts. It preserves far more JavaScript types natively:
const original = {
date: new Date(),
regex: /test/gi,
map: new Map([['key', 'value']]),
set: new Set([1, 2, 3]),
undef: undefined
};
// JSON method loses most of this
const jsonCopy = JSON.parse(JSON.stringify(original));
// date becomes string, map/set become {}, undef disappears
// structuredClone preserves them all
const structCopy = structuredClone(original);
// Everything stays the right type!
The Circular Reference Advantage
structuredClone handles circular references gracefully, while JSON throws an error:
const obj = { name: 'Alice' };
obj.self = obj; // circular reference
// JSON.stringify(obj); // ❌ TypeError: Converting circular structure
const copy = structuredClone(obj); // ✅ Works perfectly
console.log(copy.self === copy); // true
Key Takeaway: Use structuredClone for true deep cloning — it preserves more JavaScript types, handles circular references, and avoids the lossy conversion issues of the JSON round-trip trick.