Masterbook/Chapter 19• 2 min read
View Raw Code on GitHub

What is immutability and why does it matter?

What is immutability and why does it matter

Immutability means that once a value is created, it is not changed. Instead of modifying data in place, you create new values that reflect the change. JavaScript primitives (string, number, boolean, null, undefined, symbol, bigint) are immutable. Objects and arrays are mutable by default, but you can adopt immutable patterns to avoid accidental shared mutations.

Immutability reduces hidden coupling, makes reasoning and debugging easier, and helps avoid bugs where two parts of a program unintentionally affect each other through shared references. It also enables simple change detection strategies and time-travel debugging in state management libraries.

To work immutably with objects and arrays, prefer methods that return new structures such as array map, filter, slice, spread syntax for objects and arrays, and Object.assign. Use structuredClone for deep copies when needed. Object.freeze can prevent modification of an object's properties, but it is shallow and does not freeze nested objects.

Examples:

// primitive example
let a = "hi";
let b = a;
b += "!";
console.log(a, b); // "hi", "hi!"
// immutable update for object
const user = { name: "Sam", meta: { visits: 1 } };
const updated = {
  ...user,
  meta: { ...user.meta, visits: user.meta.visits + 1 },
};
// immutable array operations
const arr = [1, 2, 3];
const doubled = arr.map((x) => x * 2);
const appended = [...arr, 4];
console.log(arr, doubled, appended);

Common misconceptions

  1. const makes an object immutable. const prevents reassignment of the binding, not mutation of the object's contents.
  2. Immutability is always slower. For typical app-level data, the clarity and safety outweigh minor copying costs; libraries optimize structural sharing.
  3. JSON.stringify or Object.freeze makes deep immutability. Object.freeze is shallow; deep immutability needs recursive freezing or libraries.

Practice questions

  1. Why does immutability make state management and debugging easier?
  2. Show how to increment a deeply nested counter without mutating the original object.
  3. What tools does JavaScript provide to help you work immutably?