Lesson 4 / 25
Immutable Data and Why It Matters
No surprise changes from a distance.
The problem with shared mutable state
When two parts of a program hold a reference to the same object and one mutates it, the other sees the change without having asked for it. This "spooky action at a distance" causes bugs that are hard to trace, especially with caching, asynchronous code and UI state. With immutable data, a value never changes after creation; an "update" produces a new value. Benefits: safe sharing, simple change detection by reference (old !== new), easy undo and history, and no defensive copying. The cost is extra allocation, which structural sharing reduces.
Values that never change
Instead of modifying data in place, functional code creates new values and leaves old ones intact.
A mutation bug and its fix
Shared references make mutation visible elsewhere.
const defaults = { theme: 'light', fontSize: 14 };
// Bug: both names point to the same object
const userSettings = defaults;
userSettings.theme = 'dark';
// defaults.theme is now 'dark' as well
// Immutable update: create a new object
const defaults2 = { theme: 'light', fontSize: 14 };
const userSettings2 = { ...defaults2, theme: 'dark' };
// defaults2 is unchanged; userSettings2 is a new object
// change detection becomes a reference check:
const changed = userSettings2 !== defaults2; // trueEditing a shared document versus saving a copy
If everyone edits the same paper copy, nobody knows who changed what. If each edit produces a new version, old versions stay readable and history is free.
Quick check: What does immutability make cheap?
- Updating very large arrays in place
- Detecting changes by comparing references
- Avoiding all memory allocation
- Mutating objects shared across modules
Answer
Detecting changes by comparing references — If values never change, a different reference means different content.