π¦ Finally, True Deep Copy Without Libraries
JSON.parse(JSON.stringify()) fails with dates, undefined, functions. structuredClone() handles dates, maps, sets, arrays, nested objects β everything.
β JSON Hack (Broken)
const obj = {
date: new Date(),
fn: () => {},
undef: undefined
};
const copy = JSON.parse(JSON.stringify(obj));
// date becomes string!
// fn and undef are gone!
console.log(copy);
// { date: "2024-01-01T00:00:00.000Z" }
β structuredClone (Perfect)
const obj = {
date: new Date(),
map: new Map([[1, 'one']]),
arr: [1, [2, 3]]
};
const copy = structuredClone(obj);
// date is Date object!
// map is Map object!
// nested arrays preserved!
copy.arr[1][0] = 99;
console.log(obj.arr[1][0]); // 2 (original unchanged)
π― What structuredClone Supports
// Primitives (string, number, boolean, null)
const copy = structuredClone('hello');
// Arrays (nested works)
const arr = [1, [2, [3]]];
const arrCopy = structuredClone(arr);
// Objects (nested works)
const obj = { a: { b: { c: 1 } } };
const objCopy = structuredClone(obj);
// Dates
const date = new Date();
const dateCopy = structuredClone(date);
dateCopy.setFullYear(2025);
console.log(date.getFullYear()); // 2024 (unchanged)
// Maps
const map = new Map([['key', 'value']]);
const mapCopy = structuredClone(map);
// Sets
const set = new Set([1, 2, 3]);
const setCopy = structuredClone(set);
// ArrayBuffers, TypedArrays
const buffer = new ArrayBuffer(8);
const bufferCopy = structuredClone(buffer);
β Real-World Use Case
// React/Redux state updates
const initialState = {
user: { name: 'Alice', preferences: new Map([['theme', 'dark']]) },
lastLogin: new Date()
};
// β Before structuredClone
const newState = JSON.parse(JSON.stringify(initialState));
// lastLogin is string, preferences gone
// β
After structuredClone
const newState = structuredClone(initialState);
newState.user.name = 'Bob';
// original state unchanged, all types preserved
// Form state copy (before user edits)
const originalFormData = getFormData();
const workingCopy = structuredClone(originalFormData);
// Edit workingCopy, compare with original to detect changes
π‘ Limitations
- Does NOT copy functions (throws error)
- Does NOT copy DOM nodes (throws error)
- Does NOT copy Symbols (ignores them)
- Does NOT copy prototypes (plain objects only)
- Circular references are supported (works fine)
“Lost Date objects in Redux because JSON.stringify turned them into strings. Months of debugging. structuredClone fixed everything in one line. Native solution, no libraries.”
