Shallow copy vs deep copy — how do you make each?
Quick answer
Shallow: spread or Object.assign (nested refs shared). Deep: structuredClone (modern) or a recursive clone.
In detail
`{ ...obj }` and `Object.assign({}, obj)` copy only the top level, so nested objects stay shared. For a true deep copy use `structuredClone(obj)` (handles dates, maps, cycles) or `JSON.parse(JSON.stringify(obj))` for plain data only (loses functions, undefined, turns dates into strings).
const a = { user: { name: "x" } };
const shallow = { ...a };
shallow.user.name = "y";
a.user.name; // "y" — shared!
const deep = structuredClone(a); // fully independentWhy interviewers ask this: A real bug source interviewers want you to know.
This is 1 of 118+ questions in the JavaScript Interview Kit
Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.
⚡ Get the JavaScript Interview Kit → ₹299