Produce a fully independent copy of a nested object so mutating the copy never affects the original.
Spread and Object.assign are shallow. Use the built-in structuredClone() for a true deep copy. JSON.parse(JSON.stringify()) also deep-copies but drops functions/undefined and mangles Dates; a manual recursive clone handles custom cases.
// Modern built-in (best default):
const clone = structuredClone(obj);
// Manual recursive clone:
function deepClone(value) {
if (value === null || typeof value !== 'object') return value;
if (Array.isArray(value)) return value.map(deepClone);
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, deepClone(v)])
);
}Deep cloning isolates a base test fixture so each test can mutate its own copy without polluting shared state across the suite.
A team deep-clones config with JSON.parse(JSON.stringify(config)) and their Date field becomes a string, breaking comparisons. Why?