JavaScript · Question 8 of 50
What is the difference between a shallow copy and a deep copy?
What they're checking
References, and why it matters for React state.
The answer
A shallow copy makes a new outer object but shares everything nested: {...obj}, Object.assign and arr.slice() are all shallow. Change a nested object through the copy and the original changes too. A deep copy duplicates every level.
Today, use structuredClone(obj): it handles dates, maps, sets and circular references, though not functions. JSON.parse(JSON.stringify(obj)) turns dates into strings and drops undefined and functions. In React state, copy only the path you change: {...state, user: {...state.user, name}}.
const a = { user: { name: 'Asha' } }
const b = { ...a } // shallow
b.user.name = 'Ravi'
a.user.name // 'Ravi': shared!
const c = structuredClone(a) // deep: c.user is its own objectThe picture
shallow: a ──▶ { user: • } ──┐
b ──▶ { user: • } ──┴──▶ { name: 'Asha' } shared
deep: c ──▶ { user: • } ─────▶ { name: 'Asha' } its ownThe follow-up they'll ask
Why does React care?
Show the answer
React compares references to decide what changed. Mutating nested state keeps the same reference, so the component may not re-render.
Your progress stays on this device.