Full answer
A naive recursive clone loops forever on a cycle such as a.self = a. The fix is a memory of what has already been cloned: a WeakMap that maps each original object to its clone. Before cloning an object, look it up. If it is there, return the clone you already made. Create the empty clone and store it in the map before you copy the children, otherwise the cycle is not detected in time. A WeakMap is the right tool because it does not keep the originals alive after the clone is done.
Each type needs its own handling. A Date is rebuilt with new Date(value.getTime()). A RegExp is rebuilt from its source and flags, and lastIndex is copied. A Map and a Set are rebuilt by cloning their keys and values, which also preserves shared references inside them. An array is cloned by index. A plain object is created with Object.create(Object.getPrototypeOf(value)) so the prototype is kept, and then every own key from Reflect.ownKeys is copied, which includes symbol keys. Primitives and functions are returned as they are. Functions cannot be cloned in a meaningful way, so they are shared.
The built-in structuredClone already handles cycles, Date, Map, Set, RegExp, typed arrays, and more. It throws on functions and on DOM nodes, drops the prototype (class instances become plain objects), and ignores getters by reading their value. Write a custom clone only when you need to keep prototypes or treat functions in a special way.
Test the cases that fail most often: a cycle, two properties pointing to the same object (the clone must also share one object, not two), and a Map holding objects.
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== 'object') return value;
if (seen.has(value)) return seen.get(value);
if (value instanceof Date) return new Date(value.getTime());
if (value instanceof RegExp) {
const copy = new RegExp(value.source, value.flags);
copy.lastIndex = value.lastIndex;
return copy;
}
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;
}
const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) {
if (Array.isArray(value) && key === 'length') continue;
copy[key] = deepClone(value[key], seen);
}
return copy;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
sum() { return this.x + this.y; }
}
const shared = { n: 1 };
const tag = Symbol('tag');
const original = {
when: new Date(0),
pattern: /ab+/gi,
list: [1, [2, 3]],
map: new Map([['k', { deep: true }]]),
set: new Set([1, 2]),
point: new Point(2, 3),
a: shared,
b: shared,
[tag]: 'symbol value',
};
original.self = original;
const copy = deepClone(original);
console.log('cycle kept:', copy.self === copy, copy !== original);
console.log('shared reference kept shared:', copy.a === copy.b, copy.a !== shared);
console.log('date and regexp:', copy.when instanceof Date, copy.when !== original.when, copy.pattern.flags);
console.log('map and set:', copy.map.get('k').deep, copy.map.get('k') !== original.map.get('k'), copy.set.has(2));
console.log('prototype kept:', copy.point instanceof Point, copy.point.sum());
console.log('symbol key copied:', copy[tag]);
console.log('nested array copied:', copy.list[1] !== original.list[1], copy.list);
const viaStructured = structuredClone(original);
console.log('structuredClone cycle:', viaStructured.self === viaStructured);
console.log('structuredClone loses prototype:', viaStructured.point instanceof Point, typeof viaStructured.point.sum);
try {
structuredClone({ run() {} });
} catch (error) {
console.log('structuredClone on a function:', error.name);
}Run with Node.js v24.22.1 as js-101.js; two runs gave identical output. Output: cycle kept: true true shared reference kept shared: true true date and regexp: true true gi map and set: true true true prototype kept: true 5 symbol key copied: symbol value nested array copied: true [ 1, [ 2, 3 ] ] structuredClone cycle: true structuredClone loses prototype: false undefined structuredClone on a function: DataCloneError
Key points
- A WeakMap from original to clone detects cycles and keeps shared references shared.
- Store the clone in the map before copying children.
- Rebuild Date, RegExp, Map, and Set explicitly; use Reflect.ownKeys and keep the prototype for plain objects.
- Functions and primitives are returned as they are.
- structuredClone covers most needs but loses prototypes and throws on functions.
Common mistakes
- Forgetting the seen map and overflowing the stack on a cycle.
- Registering the clone in the map after copying children.
- Cloning objects with JSON.parse(JSON.stringify(...)), which breaks Date, Map, Set, undefined, and cycles.
- Copying Object.keys only and dropping symbol keys.
Follow-ups
- Why use a WeakMap instead of a Map for the seen record?
- How would you clone a class instance that has private fields?
- When would you prefer structuredClone over a custom function?
Tips
- Mention the cycle problem first, then the WeakMap solution.
- Test shared references, not only cycles.
- Know structuredClone limits: functions, prototypes, DOM nodes.