Here are the most reliable ways to perform a deep clone of an object in JavaScript.
Supports functions, dates, maps, sets, circular references, etc.
const deepClone = structuredClone(original);
β Fast and standard.
β Not supported in older environments (e.g., Node <17, legacy browsers).
cloneDeepimport cloneDeep from 'lodash/cloneDeep'; const deepClone = cloneDeep(original);
β Handles most edge cases.
β Works in all JS environments.
β Requires external dependency.
For full control; avoid unless necessary.
function deepClone(obj, hash = new WeakMap()) { if (Object(obj) !== obj || obj instanceof Function) return obj; if (hash.has(obj)) return hash.get(obj); // handle circular refs const result = Array.isArray(obj) ? [] : obj instanceof Date ? new Date(obj) : obj instanceof RegExp ? new RegExp(obj.source, obj.flags) : Object.create(Object.getPrototypeOf(obj)); hash.set(obj, result); for (const key of Reflect.ownKeys(obj)) { result[key] = deepClone(obj[key], hash); } return result; } // or more simply: function deepCopy(obj) { if (obj === null || typeof obj !== 'object') return obj; const newObj = Array.isArray(obj) ? [] : {}; for (const key of Object.keys(obj)) { newObj[key] = deepCopy(obj[key]); } return newObj; }
β Fine-grained control.
β Error-prone, needs frequent updates for edge cases.
JSON.parse(JSON.stringify(obj)) (Not Recommended for Complex Objects)const deepClone = JSON.parse(JSON.stringify(original));
β Strips functions,
undefined, symbols, dates, regex, etc.β Okay for simple objects only.
structuredClone if environment supports it.cloneDeep from Lodash.Let me know your runtime constraints if you want a tailored version.
Test your understanding with 3 quick questions