Immutability: Copy, Don't Mutate

Immutability: Copy, Don't Mutate in JavaScript: Imagine a shared document that ten people edit at once.

Concept Explanation

Imagine a shared document that ten people edit at once. If everyone scribbles on the same original page, nobody can tell what changed or undo a mistake. Instead, imagine each edit produces a brand-new photocopy with the change applied — the old version stays frozen forever.

That is immutability: instead of changing (mutating) an object or array in place, you build a new copy with the update. React, Redux, and every modern state library depend on this — it's how they detect "did this change?" instantly (just compare the two references) and how they power undo/redo.


Syntax or Core Structure

// ❌ Mutation — destroys the original
const state = { count: 1 };
state.count = 2; // the old value is gone forever

// ✅ Immutable — build a new object
const next = { ...state, count: 2 };
// state is still { count: 1 }, next is { count: 2 }

Arrays work the same way — use methods that return a new array:

const list = [1, 2, 3];
const added = [...list, 4];                 // add
const removed = list.filter(n => n !== 2);  // remove
const doubled = list.map(n => n * 2);       // update

Common Mistakes

  • Sneaky Mutators: push, pop, splice, and sort change the original array. Prefer concat, slice, filter, and map.
  • Shallow Copies: { ...obj } only copies the top level. Nested objects are still shared — spread each level you plan to change.
  • Mutating Props: Never edit an object passed into your function; the caller still owns it.

Best Practices

  • Freeze in Dev: Object.freeze(state) throws if you accidentally mutate, catching bugs early.
  • Reach for Tools: Libraries like Immer let you "write mutating code" that safely produces immutable copies under the hood.

Practice Exercises

  1. The Adder: Write a function that adds an item to an array without using push.
  2. The Updater: Given { user: { name: "Al" } }, return a new object with the name changed — without touching the original.
  3. The Toggle: Immutably flip a done boolean on one item in an array of todos.