Immutability Explained: Why Not Changing Data Helps
Immutable data cannot be modified after creation. Learn how it prevents whole classes of bugs, how to update it efficiently, and when to skip it.
By Velloreth
What immutability means
An immutable value cannot be changed after it is created. Any “modification” produces a new value, leaving the original untouched.
const original = { name: 'Ada', age: 36 };
const updated = { ...original, age: 37 };
original.age; // 36 — unchanged
updated.age; // 37
Note that const in JavaScript does not make an object immutable. It prevents reassigning the variable, not mutating the object:
const user = { name: 'Ada' };
user.name = 'Grace'; // allowed! const does not prevent this
Real immutability requires either discipline, Object.freeze, or a library.
The bug class it eliminates
The main reason to care about immutability is that it removes an entire category of bugs: aliasing.
function applyDiscount(order) {
order.total = order.total * 0.9; // mutates the caller's object
return order;
}
const myOrder = { total: 100 };
const discounted = applyDiscount(myOrder);
myOrder.total; // 90 — the original changed too!
The caller passed an object, the function changed it, and now two variables that were supposed to be independent are the same object. This is aliasing, and it causes bugs that are notoriously hard to trace because the mutation happens far from where the wrong value is observed.
The immutable version:
function applyDiscount(order) {
return { ...order, total: order.total * 0.9 };
}
const myOrder = { total: 100 };
const discounted = applyDiscount(myOrder);
myOrder.total; // 100 — untouched
The bug is not fixed; it is impossible. There is no way to write the mutation, so there is no way to introduce the aliasing.
Reference equality as a change check
Here is a benefit that is easy to miss and very valuable in practice.
With mutable data, checking whether something changed requires a deep comparison — walking the whole structure and comparing every field. That is O(n).
With immutable data, you compare references. If the reference is the same, nothing changed. That is O(1).
prevState === nextState; // true means nothing changed
This is exactly how React decides whether to re-render. When you pass a new object, React sees a different reference and re-renders. When you mutate the existing object and pass it again, React sees the same reference and skips the update — which is why mutating state in React silently fails to update the UI.
The same principle powers memoisation, change detection in Vue and Svelte, and undo systems.
Structural sharing
The obvious objection to immutability is cost. If every update copies the whole structure, updating one field of a large object is O(n), which is unacceptable.
Structural sharing solves this. A new version reuses the unchanged parts of the old version by reference.
const state = {
user: { name: 'Ada', email: 'ada@example.com' },
posts: [/* a thousand posts */],
settings: { theme: 'dark' },
};
// Update one field — the posts array is shared, not copied
const next = {
...state,
settings: { ...state.settings, theme: 'light' },
};
next.posts === state.posts; // true — same array, no copy
Only the objects along the path from the root to the change are copied. Everything else is shared. For a tree of depth d, an update costs O(d) instead of O(n).
This is what persistent data structures formalise. A persistent list or map keeps every previous version available while sharing most of the memory between them.
Immutability in different languages
| Language | Default | Notes |
|---|---|---|
| JavaScript | Mutable | const prevents reassignment only |
| Python | Mutable | Tuples, strings, frozensets are immutable |
| Java | Mutable | final prevents reassignment only |
| Rust | Mutable | Immutable by default; mut opts in |
| Go | Mutable | No language support |
| Clojure | Immutable | Persistent structures built in |
| Haskell | Immutable | Purely functional |
| Elixir | Immutable | All data is immutable |
Rust is the interesting case: variables are immutable unless declared mut, which inverts the usual default. The compiler then enforces that only one mutable reference exists at a time, eliminating data races at compile time.
How to update immutably
Objects
// Shallow update
const next = { ...prev, name: 'Grace' };
// Nested update
const next = {
...prev,
address: { ...prev.address, city: 'Kathmandu' },
};
Arrays
const added = [...items, newItem]; // append
const removed = items.filter((i) => i.id !== target); // remove
const updated = items.map((i) => i.id === target ? { ...i, done: true } : i);
Note that push, pop, splice, and sort all mutate. The immutable alternatives are spread, filter, map, slice, and toSorted.
With a library
Nested spreads get unwieldy fast. Immer lets you write mutating code and produces an immutable result:
import { produce } from 'immer';
const next = produce(state, (draft) => {
draft.settings.theme = 'light';
draft.posts.push(newPost);
});
// state is unchanged; next is a new immutable object
Immer uses a proxy to record the mutations and applies them to a copy, with structural sharing. It is the pragmatic middle ground for JavaScript applications.
Immutability and concurrency
In a multi-threaded program, shared mutable state is the source of data races. Two threads writing to the same object produce results that depend on timing, which is the hardest class of bug to reproduce.
Immutable data cannot be mutated, so it cannot be raced. Threads can share references freely, and the only synchronisation needed is for the reference itself.
This is why functional languages lean on immutability, and why Rust’s ownership model is built around it. It is also why immutable data is natural in distributed systems: a value that cannot change can be replicated without coordination.
The costs
Immutability is not free.
Allocation pressure. Every update allocates. In a hot loop, that creates garbage-collection pressure, which costs time in a way complexity analysis does not capture.
Memory. Keeping old versions alive uses memory. An undo history of a large structure can be expensive, though structural sharing limits it.
Verbosity. Nested spreads are noisy. Libraries help, but they add a dependency and a learning curve.
Not always natural. Some algorithms are inherently in-place — sorting, matrix operations, image processing. Forcing immutability there produces slower, less readable code.
When to use it
Use immutability for:
- Application state, especially in UI frameworks.
- Configuration and constants.
- Data shared between components or threads.
- Anything that needs history or undo.
- Values passed across module boundaries.
Skip it for:
- Large numeric buffers and typed arrays.
- Hot loops where allocation dominates.
- In-place algorithms like sorting.
- Short-lived local variables inside a function.
The practical rule: immutable at the boundaries, mutable inside. A function can mutate its own local variables freely; what it must not do is mutate its arguments or shared state.
Practical guidance
- Treat function arguments as read-only. If you need to change them, copy first.
- Return new values from transformations.
mapandfilteralready do this;sortandsplicedo not. - Use
Object.freezein development to catch accidental mutations early. It is slow in production, so gate it on the environment. - Reach for Immer when nested updates get painful.
- Do not fight the language. In Rust, embrace the borrow checker. In JavaScript, use the spread operator and accept the verbosity.
- Remember that
constis not immutability. It prevents reassignment, not mutation.
For the related idea of functions that change nothing, see pure functions and side effects. For how immutability shapes design, dependency injection without a framework and technical debt conversation.
Quotable summary
Immutable data cannot be changed after creation, so updates produce a new value and leave the original intact. Immutability eliminates aliasing bugs, where two references to the same object cause one part of a program to change data another part depends on. It makes change detection O(1) through reference equality, which is how React decides whether to re-render. Structural sharing keeps updates cheap by reusing unchanged subtrees, so updating one field of a large structure costs O(depth) rather than O(size). The costs are allocation pressure, memory, and verbosity, so immutability is a strong default for application state and a poor fit for hot loops and large numeric buffers.