Shallow Copy vs Deep Copy in JavaScript
A real source of bugs, especially in React. The difference is what happens to nested objects.
The difference
A shallow copy ({ ...obj } or Object.assign) copies only the top level — nested objects stay shared by reference. A deep copy duplicates everything, so the copy is fully independent.
const shallow = { ...a };
shallow.user.name = "y"; // mutates a.user too (shared!)
const deep = structuredClone(a); // fully independentHow to deep copy
Use structuredClone(obj) (handles dates, maps, cycles). JSON.parse(JSON.stringify(obj)) works for plain data only — it drops functions and undefined and mangles dates. Or write a recursive clone.
Avoid the reference-vs-value bugs
Copying, immutability and the object questions interviewers ask — in the JavaScript Interview Kit.
⚡ Get the JavaScript Interview Kit → ₹299Frequently asked questions
- Why does mutating a shallow copy change the original?
- Because nested objects are shared by reference — only the top level was copied.
- Is spread a deep copy?
- No — spread is shallow. Nested objects remain shared. Use structuredClone for a deep copy.
