structuredClone for deep copies
| 1 min read
For years the go-to deep-clone trick was JSON.parse(JSON.stringify(obj)). It works for plain data, but the moment your object contains a Date, a Map, a Set, undefined, or a circular reference, things quietly fall apart.
Modern browsers (and Node 17+) ship structuredClone which handles all of that for you.
const original = {
name: "Rohan",
joined: new Date("2016-06-01"),
tags: new Set(["css", "js"]),
meta: { count: 42 },
};
const copy = structuredClone(original);
copy.meta.count = 100;
console.log(original.meta.count); // 42 — original untouched
console.log(copy.joined instanceof Date); // true — Date preserved
It even handles cycles —
const a = { name: "a" };
a.self = a;
const b = structuredClone(a); // works, no stack overflow
What it can’t clone: functions, DOM nodes, prototypes (the result is a plain object), and a few other non-serializable things. For 99% of state objects though, it’s exactly what you want.