How do you implement a deep clone function?
A deep clone copies an object and all nested levels, so the copy shares nothing with the original.
structuredClone() — the modern built-in; handles nested objects, Dates, Maps, and circular references.
Recursion — walk the structure, cloning arrays and objects level by level.
JSON trick — JSON.parse(JSON.stringify(obj)) works for plain data but loses dates, functions, and undefined.
Prefer structuredClone() unless you must support very old environments.
// Method 1: structuredClone (recommended, 2022+)
const deep1 = structuredClone(original);
// Method 2: JSON round-trip (simple, lossy)
const deep2 = JSON.parse(JSON.stringify(original));
// Loses: functions, undefined, Date (→ string), NaN, Infinity
// Method 3: Recursive (customizable)
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (Array.isArray(obj)) return obj.map(item => deepClone(item));
const clone = {};
for (const key of Object.keys(obj)) {
clone[key] = deepClone(obj[key]);
}
return clone;
}
// Test
const original = {
name: 'John',
date: new Date(),
nested: { deep: { value: 42 } },
arr: [1, [2, 3]]
};
const cloned = deepClone(original);
cloned.nested.deep.value = 99;
console.log(original.nested.deep.value); // 42 — independent!structuredClone handles most types correctly (recommended). JSON round-trip is simple but loses many types.
The recursive function handles Date and RegExp explicitly, recurses into arrays (map) and objects (for...of keys). Each nested value is cloned independently.
structuredClone is the modern answer (2022+). JSON round-trip for quick-and-dirty (know the limitations). The recursive function shows algorithmic thinking.
Handle Date and RegExp as special cases. Mention circular reference handling for advanced credit.