structuredClone() Finally Kills the JSON.parse(JSON.stringify()) Hack
A bug report came in once where saved drafts kept losing their scheduled dates. The culprit was a line I'd written myself: JSON.parse(JSON.stringify(draft)). The Date object inside went in as a Date and came out as a string, and the code downstream quietly did the wrong thing with it.
The JSON round-trip has always been a lossy way to copy:
- Date objects become ISO strings
- Map and Set become empty objects
- undefined values disappear entirely
- NaN and Infinity become null
- circular references throw an exception
The platform fix is one function:
const copy = structuredClone(draft);
copy.scheduledAt instanceof Date; // true - still a real Date
copy.tags instanceof Set; // true - Sets survive
copy.meta.parent === copy; // circular references work too
What it can and cannot clone
structuredClone() uses the same algorithm the browser uses for postMessage() and IndexedDB. It handles plain objects, arrays, Date, RegExp, Map, Set, ArrayBuffer, typed arrays, Blob, File and more, including arbitrarily nested and circular structures.
It will throw on two things: functions and DOM nodes. If your object carries methods, that's usually a sign you want a proper class with its own clone logic rather than a structural copy. Prototypes are also not preserved - a cloned class instance comes back as a plain object.
It's also surprisingly useful for "freezing" state
When debugging, console.log(state) shows a live reference - by the time you expand it in DevTools, it may have changed. Logging structuredClone(state) pins the exact snapshot at that moment. That one trick has saved me from several "but it says X in the log" arguments with myself.
Support: Chrome 98+, Firefox 94+, Safari 15.4+, Node 17+. At this point the JSON hack is legacy code. When you spot it in review, you know what to suggest.
Full-stack web developer sharing practical tutorials and building tools that ship.
Got something on your mind?
My inbox is open - no forms disappearing into the void here.
- Just say hello Found a tutorial useful? Spotted a mistake? Tell me.
- Hire me for a project Have something custom in mind? Let's talk scope and timelines.
- Product support Bought something here? I'll help you get it running.
I usually reply within 1-2 business days.