Mutability and Immutability

Data that can change in place versus data that never changes, and why immutable data makes programs easier to reason about.

What is it?

A mutable value can be changed after it's created: you can append to a list, set a field on an object, or overwrite an array element. An immutable value can't: any "change" produces a new value and leaves the original untouched.

In Python, list, dict and set are mutable; int, float, str, tuple and frozenset are immutable. In JavaScript, primitives (numbers, strings, booleans) are immutable while objects and arrays are mutable. Rust makes every variable immutable unless you write mut.

Note the difference between an immutable binding and an immutable value. JavaScript's const and Java's final stop you from re-assigning the variable, but the object it points to can still be changed.

Immutable data removes a whole category of bugs: if nothing can change, no other part of the program can surprise you by changing it.

Explain like I'm 10

A mutable value is a whiteboard: anyone with access can erase and rewrite it, so what you read depends on who was there last. An immutable value is a printed page: to change it you print a new edition, and anyone holding the old edition still sees exactly what they had.

Examples

Mutating vs creating new values (JavaScript)

const scores = [3, 1, 2];

// Mutating: changes the original array
scores.sort();              // scores is now [1, 2, 3]

// Non-mutating: returns a new array, original untouched
const original = [3, 1, 2];
const sorted = original.toSorted();     // [1, 2, 3]
const withFour = [...original, 4];      // [3, 1, 2, 4]
console.log(original);                  // [3, 1, 2]

const user = Object.freeze({ name: "Ana", tags: ["a"] });
user.name = "Bo";        // ignored (TypeError in strict mode)
user.tags.push("b");     // works! freeze is shallow

Immutable records in Python

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
# p.x = 5             # FrozenInstanceError
moved = replace(p, x=5)   # a new Point(5, 2); p is still Point(1, 2)

name = "ana"
upper = name.upper()      # strings are immutable: a new string is returned
print(name, upper)        # ana ANA

Defensive copying at a boundary

class Team:
    def __init__(self, members):
        self._members = list(members)   # copy in: caller can't change our state

    @property
    def members(self):
        return tuple(self._members)     # copy out: caller gets a read-only view

names = ["ana", "bo"]
team = Team(names)
names.append("eve")       # does not affect team
print(team.members)       # ('ana', 'bo')

Defensive copying protects an object's internal state from callers who keep a reference to the data they passed in or got back.

How it works

For an immutable value, every "update" operation allocates a new value. Naively that means copying everything, which would be slow for large collections. Persistent data structures solve this with structural sharing: the new version reuses most of the old version's internal nodes and only creates new nodes along the path that changed. Updating one element of a persistent vector with a million items copies a handful of small nodes, not a million elements. Clojure's collections, Immutable.js and Scala's immutable collections work this way.

Language support varies:

- Rust: immutable by default; mut opts in. The borrow checker also forbids mutation while other references exist. - Python: immutable built-in types, frozen=True dataclasses, tuples. - JavaScript: Object.freeze (shallow), non-mutating array methods (map, filter, toSorted, with), spread syntax. - Java: final fields, record classes, List.of(...) unmodifiable collections.

Structural sharing: update index 3 in a persistent tree

     old root               new root
       /   \                  /   \
     A       B    ------>   A      B'     only the path to the
    / \     / \            (shared) / \     changed leaf is copied
   1   2   3   4                   3'  4  (4 is shared)

Why does it exist?

Shared mutable state is the root of many bugs: an object changed by code you didn't expect, a list modified while being iterated, data races between threads. Immutable values can be shared freely, cached safely, used as dictionary keys, compared cheaply by reference, and reasoned about locally. They also make undo/redo, time-travel debugging and change detection (as in React) straightforward: if the reference changed, the data changed.

When to use it

Prefer immutable data for configuration, values passed between modules, state shared across threads, keys in hash maps, and application state in UI frameworks that compare references. Use const/final/non-mut bindings by default and make something mutable only when it needs to be.

When not to use it

Inside a tight loop that builds up a large result (filling a buffer, accumulating a big list), local mutation is simpler and faster than creating a new collection each step. That mutation is safe as long as the mutable object doesn't escape the function. Repeated string concatenation in a loop is a classic case: build a list and join it instead.

Common mistakes

  • Believing const in JavaScript makes an object immutable. It only prevents re-assigning the variable.

  • Relying on Object.freeze for nested data. It's shallow: nested objects and arrays remain mutable.

  • Mutating props or state directly in React (e.g. state.items.push(x)), so the reference doesn't change and the UI doesn't re-render.

  • Using a mutable object (a list or dict) as a dictionary key or set member in Python, which raises TypeError: unhashable type.

  • Building a large string with += in a loop, creating a new string every iteration instead of joining a list once.

Practice exercises

  1. Easy:

    Rewrite a function that adds an item to a shopping cart by calling cart.push(item) so that it returns a new cart and leaves the original unchanged.

  2. Medium:

    Write deepFreeze(obj) in JavaScript that recursively freezes an object and all nested objects and arrays. Test that nested mutations fail in strict mode.

  3. Hard:

    Implement a persistent (immutable) singly linked list with prepend, head and tail. Show that prepending to a list of length n creates one new node and shares the rest.

Interview questions

What is the difference between mutable and immutable data?

Mutable data can be modified in place after creation. Immutable data can't; every modification produces a new value and the original stays the same.

Does `const` make an object immutable in JavaScript?

No. const prevents re-assigning the variable, but the object it refers to can still be mutated. Use Object.freeze (shallow) or immutable update patterns for the value itself.

Which built-in Python types are immutable?

int, float, complex, bool, str, bytes, tuple, frozenset and None. A tuple is only as immutable as its contents: a tuple holding a list can't be re-pointed but the list can still change.

Why must dictionary keys be immutable in Python?

A dict stores keys by their hash. If a key's contents changed, its hash would change and the dict could no longer find it. So keys must be hashable, which for built-ins means immutable.

What are the main benefits of immutability?

No surprise changes from aliases, safe sharing between threads without locks, easy caching and memoisation, cheap change detection by reference comparison, and simpler reasoning and testing.

What is a persistent data structure?

An immutable data structure where an update returns a new version while keeping the old one intact, usually sharing most of the internal structure between versions so updates stay cheap (often O(log n)).

What is structural sharing?

Reusing the unchanged parts of an existing immutable structure in a new version. Only nodes on the path to the change are copied, so memory and time costs stay small.

What is defensive copying?

Copying mutable data when it enters or leaves an object, so callers can't change the object's internal state through a reference they kept or received.

Is immutability always slower?

Not necessarily. Allocating new values costs something, but structural sharing keeps it small, and immutability enables optimisations like skipping work when references are equal. For hot local loops, controlled mutation is usually faster.

How does Rust handle mutability?

Variables are immutable by default and need mut to change. The borrow checker allows either many shared (&T) references or one mutable (&mut T) reference at a time, which rules out data races at compile time.