Skip to content
Velloreth
Programming 7 min read

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

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

LanguageDefaultNotes
JavaScriptMutableconst prevents reassignment only
PythonMutableTuples, strings, frozensets are immutable
JavaMutablefinal prevents reassignment only
RustMutableImmutable by default; mut opts in
GoMutableNo language support
ClojureImmutablePersistent structures built in
HaskellImmutablePurely functional
ElixirImmutableAll 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. map and filter already do this; sort and splice do not.
  • Use Object.freeze in 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 const is 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.

Frequently asked questions

What does immutable mean in programming?
Immutable means a value cannot be changed after it is created. To 'modify' it you create a new value with the change applied, leaving the original intact. Strings in most languages are immutable; arrays usually are not.
Why is immutability useful?
It removes a whole class of bugs caused by shared mutable state, makes change detection cheap through reference equality, makes code safe to share across threads, and makes history and undo trivial because every previous version still exists.
Is immutability slow?
Naive copying is, because copying a large structure on every update is O(n). With structural sharing, only the changed path is copied, which is O(log n) for tree-shaped data. Libraries like Immer and Immutable.js implement this.
What is structural sharing?
Structural sharing means a new version of a data structure reuses the unchanged parts of the old version instead of copying them. Updating one field of a large object creates a new object that shares references to all the untouched nested values.
How do I update an immutable object in JavaScript?
Use the spread operator to create a new object with the change applied, such as { ...user, name: 'new' }. For nested updates, spread at each level, or use a library like Immer that lets you write mutating code and produces an immutable result.
Should all data be immutable?
No. Immutability is a strong default for application state, configuration, and anything shared between components. It is a poor fit for large buffers, hot loops, and performance-critical numeric code, where in-place mutation is the right choice.