What is the difference between a shallow copy and a deep copy of an object? Name ways to make each, and their limits.
Show the explanation
Model answer. A shallow copy creates a new top-level object, but nested objects are still shared with the original. A deep copy duplicates every level, so nothing is shared.
const original = { name: 'Asha', marks: { maths: 90 } };
const shallow = { ...original }; // or Object.assign({}, original)
shallow.marks.maths = 50;
original.marks.maths; // 50: nested object was shared
const deep = structuredClone(original); // modern built-in deep copy
deep.marks.maths = 70;
original.marks.maths; // still 50Ways and limits:
- Spread / `Object.assign`: shallow only.
- `structuredClone`: deep; handles dates, maps, sets and cycles, but not functions or DOM nodes.
- `JSON.parse(JSON.stringify(x))`: deep but lossy: drops functions and
undefined, turns dates into strings, fails on cycles andBigInt.
In state management (React, Redux) you usually copy only the path you change, instead of deep-copying everything.
Original UniCircle question. Last reviewed 22 Oct 2026.
