Value vs reference, and shallow vs deep copy
EasyJavaScriptTypesCopying
What's the difference between value and reference types in JavaScript, and between a shallow and a deep copy?
TL;DR
Primitives (string, number, boolean, null, undefined, bigint, symbol) are copied by value: assigning one gives you an independent copy. Objects (including arrays and functions) are accessed by reference: assigning one copies the reference, so both variables point to the same object. A shallow copy creates a new top-level object but shares nested objects. A deep copy duplicates everything.
Key points
===on objects compares references, not contents:{} === {}isfalse.- Functions receive a copy of the reference. Mutating the argument affects the caller; reassigning it doesn't.
- Shallow copy: spread (
{ ...obj },[...arr]),Object.assign,Array.from,slice. - Deep copy:
structuredClone(obj). It handlesDate,Map,Setand circular references, but not functions or class instances' prototypes. JSON.parse(JSON.stringify(obj))is the old trick: it dropsundefinedand functions and turnsDateinto a string.
Example
js
const a = { user: { name: 'Dana' } }
const shallow = { ...a }
shallow.user.name = 'Noa'
a.user.name // 'Noa': nested object is shared
const deep = structuredClone(a)
deep.user.name = 'Tal'
a.user.name // still 'Noa'Common follow-ups
- Why does this matter in React? State updates must create new references (
setItems([...items, x])). Mutating in place keeps the same reference, so React may skip the re-render. - Is JavaScript pass-by-reference? No. It's always pass-by-value; for objects, the value is a reference.
What interviewers look for
Tip
Name structuredClone for deep copies, and connect references to React's immutable state updates.
- Red flag: thinking the spread operator makes a deep copy.