Mutability & References

Difficulty
Importance

The problem

When two names can refer to the same underlying data, changing the data through one name silently changes what the other name sees — a frequent source of bugs unless you understand exactly when values are copied versus shared.

Why now

Variables and state establish that a name is bound to a value, but not whether that binding is a private copy or a shared pointer to the same data. Once arrays and lists introduce values large enough that copying them is expensive, languages start passing references instead — and functions-and-relations already showed that two names mapping to the same object is just a non-injective relation, not a special case.

Mental model

A primitive value (number, boolean) is copied on assignment — two names, two independent boxes. An object or array is instead a label pointing at a box elsewhere — assignment copies the pointer, not the box, so two names can point at the same mutable box. Every 'I changed one and the other one changed too' bug is exactly this.

Requires

Helps

Unlocks

Related

Used in

Projects

  • Write a function that mutates an array argument and one that returns a new array instead; demonstrate the difference on the caller's original data
  • Implement a deep-clone function for nested objects/arrays without using a library, handling the aliasing correctly

Examples

  • let a = [1,2]; let b = a; b.push(3); — a is now [1,2,3] too, because a and b reference the same array
  • React's setState([...oldArray, newItem]) creates a new reference specifically to avoid this aliasing trap

Resources

Mastery checklist