Full answer
Why not JSON
- JSON.stringify turns Date into a string, drops undefined and functions, turns Map and Set into {}, turns NaN and Infinity into null, and throws on circular references and BigInt.
Writing it
- Return primitives (and functions, by reference) as they are.
- Keep a WeakMap from original to copy. If an object was seen already, return its copy. This handles cycles and also keeps shared references shared.
- Create the empty copy and register it in the WeakMap before copying children (important for cycles).
- Copy by type: Array (map the items), Date (new Date(value)), RegExp (keep source, flags, reset lastIndex), Map and Set (clone keys and values), plain objects (copy own enumerable string and symbol keys, keep the prototype with Object.create(Object.getPrototypeOf(x))).
- Decide about special cases: class instances with private fields cannot be copied by key copying, getters, non-enumerable properties and typed arrays.
structuredClone
- Built in since Node 17. Handles cycles, Date, RegExp, Map, Set, ArrayBuffer, typed arrays and many errors. Throws DataCloneError on functions and some host objects, and class instances become plain objects (the prototype is lost).
- For configuration and message data, prefer structuredClone. Write your own only for special needs.
javascript
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== 'object') return value; // primitives and functions
if (seen.has(value)) return seen.get(value);
if (value instanceof Date) return new Date(value.getTime());
if (value instanceof RegExp) return new RegExp(value.source, value.flags);
if (value instanceof Map) {
const copy = new Map(); seen.set(value, copy);
for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen));
return copy;
}
if (value instanceof Set) {
const copy = new Set(); seen.set(value, copy);
for (const v of value) copy.add(deepClone(v, seen));
return copy;
}
if (Array.isArray(value)) {
const copy = []; seen.set(value, copy);
value.forEach((item, i) => { copy[i] = deepClone(item, seen); });
return copy;
}
const copy = Object.create(Object.getPrototypeOf(value)); seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor.enumerable) copy[key] = deepClone(value[key], seen);
}
return copy;
}
const shared = { n: 1 };
const original = {
date: new Date('2026-12-04T00:00:00Z'), pattern: /ab+c/gi, list: [1, [2, 3]], map: new Map([['k', { v: 1 }]]), set: new Set([1, 2]),
missing: undefined, a: shared, b: shared, [Symbol.for('id')]: 7,
};
original.self = original; // a circular reference
const copy = deepClone(original);
console.log('different objects :', copy !== original, copy.list[1] !== original.list[1], copy.map.get('k') !== original.map.get('k'));
console.log('types kept :', copy.date instanceof Date, copy.pattern.flags, copy.map instanceof Map, copy.set.has(2), 'missing' in copy);
console.log('cycle kept :', copy.self === copy);
console.log('shared reference kept :', copy.a === copy.b, '| symbol key copied:', copy[Symbol.for('id')]);
const json = (() => { try { return JSON.parse(JSON.stringify({ date: original.date, missing: undefined, map: original.map })); } catch (e) { return e.message; } })();
console.log('JSON round trip :', JSON.stringify(json));
console.log('JSON with a cycle :', (() => { try { JSON.stringify(original); } catch (e) { return e.name; } })());
const viaBuiltIn = structuredClone(original);
console.log('structuredClone cycle :', viaBuiltIn.self === viaBuiltIn, '| Map kept:', viaBuiltIn.map instanceof Map);
console.log('structuredClone + fn :', (() => { try { structuredClone({ f() {} }); } catch (e) { return e.name; } })());A cyclic object with several types is cloned, then compared with a JSON round trip and with structuredClone. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): different objects : true true true types kept : true gi true true true cycle kept : true shared reference kept : true | symbol key copied: 7 JSON round trip : {"date":"2026-12-04T00:00:00.000Z","map":{}} JSON with a cycle : TypeError structuredClone cycle : true | Map kept: true structuredClone + fn : DataCloneError
Key points
- JSON round trips lose many types and fail on cycles.
- Use a WeakMap to handle cycles and shared references.
- Register the copy before copying its children.
- Handle Date, RegExp, Map, Set and arrays explicitly.
- structuredClone is the built-in answer, except for functions and prototypes.
Common mistakes
- Using JSON.parse(JSON.stringify(x)) for data that has dates, maps or cycles.
- Recursing forever on circular references.
- Copying the copy only after its children (the cycle then breaks).
- Expecting structuredClone to copy functions or class prototypes.
- Cloning big objects on a hot path.
Follow-ups
- What does structuredClone do with a class instance?
- How would you clone typed arrays and buffers?
- When is a shallow copy with spread enough?
Tips
- Start with the JSON problems.
- Say 'WeakMap for cycles'.
- Finish with structuredClone.