Reference vs Value Theory
JavaScript primitives are copied by value while objects are handled through references to heap allocations, which explains shared mutation and copy behavior.
What it is
Primitive assignments and argument passing copy the actual primitive value, so later changes to one variable do not affect the other.
Objects and arrays are stored in memory locations, and variables hold references to those locations. Copying such variables copies the reference, not the object contents.
Understanding this distinction is essential for predictable state updates, immutability patterns, and avoiding accidental side effects.
Interview framing: define Reference vs Value in one sentence, then explain one concrete runtime behavior and one common pitfall with a short code example.
How it works
- Step 1: primitive assignment creates an independent value copy.
- Step 2: object assignment copies a reference to the same underlying object.
- Step 3: mutating a shared object through one reference is visible from all references.
- Step 4: shallow-copy operations clone only top-level properties, keeping nested references shared unless deep cloning is used.
Common mistakes
Assuming object assignment makes a deep copy
const b = a for objects means both variables point to the same object, so mutation through one affects the other.
Fix: Use copy utilities and immutable update patterns when independent objects are needed.
Relying on shallow spread for nested isolation
Object and array spread copy only one level, leaving nested objects shared by reference.
Fix: Deep clone nested structures intentionally with structuredClone or custom copy logic.
Mutating function arguments unexpectedly
Passing an object into a function passes its reference, so in-function mutation can leak outside.
Fix: Clone inputs or keep functions pure when mutation side effects are undesired.
Interview questions
Common interview prompts with concise model answers.
Are arrays passed by reference in JavaScript?
JavaScript passes values. For arrays and objects, that value is a reference to the underlying object.
const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // 2 (shared object identity)What is the fastest safe deep-copy option?
structuredClone is a solid built-in for many cases, but compatibility and data-shape constraints should be considered.
How can I check if two variables reference the same object?
Strict equality compares object identity, so a === b is true when both references point to the same object.
Does Object.freeze make nested objects immutable too?
No. freeze is shallow and does not recursively freeze nested objects unless you do so manually.
Related concepts
Continue with these concepts to strengthen your mental model.