JavaScriptMedium
What is immutability?
Immutability means never changing a value after it is created; instead of modifying data in place you create a new version with the changes, which makes state changes explicit and easy to detect.
Primitives vs objects
Primitives (strings, numbers, booleans) are already immutable: str.toUpperCase() returns a new string. Objects and arrays are mutable, so immutability for them is a discipline you choose.
Why it matters
- Change detection: React, Redux, memoisation and many caches compare by reference (
prev === next). If you mutate in place the reference stays the same and the UI does not update. - Predictability: no hidden changes from other parts of the program holding the same reference.
- Undo/redo and time travel: keep old versions around cheaply.
- Safer concurrency with workers and async code.
Tools for immutable updates
- Spread:
{ ...obj, key: value },[...arr, item]. - Non-mutating array methods:
map,filter,slice,concat, and ES2023'stoSorted,toReversed,toSpliced,with. structuredClonefor a full deep copy.- Libraries like Immer let you write "mutating" code that produces immutable updates.
Object.freezeto enforce it (shallow only).
Cost
Copying creates new objects, but only the changed path is copied; unchanged nested objects are shared (structural sharing). For typical UI state this is cheap.
Code example
js
1const state = {2 user: { name: "Ada", settings: { theme: "light" } },3 todos: [{ id: 1, done: false }, { id: 2, done: false }],4};56// Update a nested value without mutating anything7const next = {8 ...state,9 user: { ...state.user, settings: { ...state.user.settings, theme: "dark" } },10 todos: state.todos.map((t) => (t.id === 2 ? { ...t, done: true } : t)),11};1213console.log(state.user.settings.theme, next.user.settings.theme); // light dark14console.log(state === next, state.todos === next.todos); // false false15console.log(state.todos[0] === next.todos[0]); // true - unchanged items are shared1617// Reference checks detect changes instantly18const changed = (a, b) => a !== b;19console.log(changed(state.user, next.user)); // true2021// ES2023 non-mutating array methods22const nums = [3, 1, 2];23console.log(nums.toSorted(), nums.toReversed(), nums.with(0, 9), nums); // original unchanged2425// Freeze to enforce (shallow)26const frozen = Object.freeze({ list: [1] });27frozen.list.push(2); // allowed: freeze is shallow28console.log(frozen.list); // [1, 2]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.