How do you deep copy an object in JavaScript?
Use structuredClone() for deep copies in modern environments. For shallow copies, use the spread operator or Object.assign().
JavaScript
Overview
Objects and arrays in JavaScript are assigned by reference, not by value. Copying with `=` just creates another pointer to the same object. Understanding shallow vs deep copies prevents hard-to-find mutation bugs.
Key Points
- •Shallow copy: top-level properties are copied, but nested objects still share references.
- •Deep copy: a completely independent clone changes to the copy do not affect the original.
- •`structuredClone(obj)` is the native deep copy solution (supported in all modern browsers and Node 17+).
- •Spread `{ ...obj }` and `Object.assign({}, obj)` create shallow copies only.
- •JSON round-trip (`JSON.parse(JSON.stringify(obj))`) works but loses `undefined`, `Date`, `function`, `RegExp`, and circular references.
Examples
The reference problem
javascriptconst original = { a: 1, nested: { b: 2 } };
const copy = { ...original }; // shallow copy
copy.a = 99; // original.a is still 1 (top level OK)
copy.nested.b = 99; // original.nested.b is NOW 99 shared reference!Deep copy with structuredClone (modern, recommended)
javascriptconst original = { a: 1, nested: { b: 2 } };
const deep = structuredClone(original);
deep.nested.b = 99;
console.log(original.nested.b); // still 2 fully independentShallow copy options
javascript// Spread (ES2018+)
const shallowObj = { ...original };
const shallowArr = [...original];
// Object.assign
const copy = Object.assign({}, original);JSON round-trip (works, but with limitations)
javascriptconst deep = JSON.parse(JSON.stringify(original));
// Loses: undefined values, Date objects, functions, RegExp, circular refsUse structuredClone instead it handles Dates, Maps, Sets, and circular references.
Pro Tip
Use `structuredClone()` for deep copies. Use spread or `Object.assign` for shallow copies when you know the object is flat. Avoid the JSON trick in new code `structuredClone` is strictly better.