← Back to JavaScript, page 4

javascript-0073 · Medium mid

How do you update objects and arrays immutably in JavaScript, and why does it matter for change detection?

Immutable updates build new objects and arrays instead of changing existing ones, using spread, map, filter, and the non-mutating methods toSorted, toReversed, toSpliced, and with. Parts that did not change keep their references, so a cheap Object.is check on identity can tell whether anything changed. UI libraries rely on this for fast change detection.

Full answer

A mutation changes a value in place, such as list.push(1) or user.age = 30. An immutable update leaves the old value untouched and returns a new one. This keeps history intact, avoids bugs where two parts of a program share and silently change the same data, and makes change detection cheap: if the reference is the same, nothing changed.

For objects, spread copies the top level and then overrides keys: { ...user, age: 30 }. For nested data, copy every level on the path to the change and reuse the rest: { ...state, user: { ...state.user, address: { ...state.user.address, city: 'Delhi' } } }. The parts off that path keep their original references, which is called structural sharing.

For arrays, add with [...list, item], remove with filter, change one item with map, and use the ES2023 methods that return copies: toSorted, toReversed, toSpliced, and with(index, value). Compare these with sort, reverse, splice, and push, which mutate.

Change detection then reduces to Object.is(oldValue, newValue). React's state, memoization, and dependency checks and Redux-style stores depend on this. If code mutates and reuses the reference, the check says "unchanged" and the screen does not update.

Spread is shallow, so updating deep structures by hand becomes long. Helper libraries or the structuredClone function can help, but a full deep clone loses structural sharing and costs more. Object.freeze in development can catch accidental mutations, though it is shallow.

javascript
const state = {
  user: { name: 'Asha', address: { city: 'Pune', pin: '411001' } },
  courses: ['HTML', 'CSS', 'JS'],
  settings: { theme: 'light' },
};

const next = {
  ...state,
  user: { ...state.user, address: { ...state.user.address, city: 'Delhi' } },
};
console.log(state.user.address.city, next.user.address.city);
console.log('changed branch:', next.user !== state.user, next.user.address !== state.user.address);
console.log('shared branches:', next.settings === state.settings, next.courses === state.courses);

const list = [3, 1, 2];
console.log(list.toSorted(), list.toReversed(), list.with(0, 99), list.toSpliced(1, 1), list);
const withItem = [...list, 4];
const without = list.filter((n) => n !== 1);
const replaced = list.map((n) => (n === 2 ? 20 : n));
console.log(withItem, without, replaced, list);

const mutated = state.courses;
mutated.push('React');
console.log(Object.is(mutated, state.courses), 'same reference: a change check would miss it');

function updateIfChanged(old, key, value) {
  return Object.is(old[key], value) ? old : { ...old, [key]: value };
}
const unchanged = updateIfChanged(state.settings, 'theme', 'light');
const changed = updateIfChanged(state.settings, 'theme', 'dark');
console.log(unchanged === state.settings, changed === state.settings, changed);

const frozen = Object.freeze({ count: 1, nested: { value: 1 } });
try {
  (function () {
    'use strict';
    frozen.count = 2;
  })();
} catch (error) {
  console.log('mutation caught:', error.name);
}
frozen.nested.value = 2; // freeze is shallow
console.log(frozen.nested.value);

const replacedCourses = state.courses.map((c) => (c === 'CSS' ? 'Sass' : c));
console.log(replacedCourses, state.courses);

Run with Node.js v24.22.1 as js-73.js; two runs gave identical output. Output: Pune Delhi changed branch: true true shared branches: true true [ 1, 2, 3 ] [ 2, 1, 3 ] [ 99, 1, 2 ] [ 3, 2 ] [ 3, 1, 2 ] [ 3, 1, 2, 4 ] [ 3, 2 ] [ 3, 1, 20 ] [ 3, 1, 2 ] true same reference: a change check would miss it true false { theme: 'dark' } mutation caught: TypeError 2 [ 'HTML', 'Sass', 'JS', 'React' ] [ 'HTML', 'CSS', 'JS', 'React' ]

Key points

  • Immutable updates return new values and leave the old ones unchanged.
  • Copy each level along the path to the change; share the rest.
  • Use map, filter, spread, toSorted, toReversed, toSpliced, and with for arrays.
  • Identity checks with Object.is make change detection cheap.
  • Spread and freeze are shallow; a full deep clone loses sharing.

Common mistakes

  • Believing spread makes a deep copy and mutating nested objects of the copy.
  • Mutating state and keeping the same reference, so change checks see no change.
  • Deep cloning the whole state for each update and losing structural sharing.
  • Using sort or reverse on shared arrays, which change the original.

Follow-ups

  • How does a library like Immer let you write mutating code and still produce immutable results?
  • What is the cost of copying a large array on every update, and how do persistent data structures help?
  • How does React decide whether to re-render when state is an object?

Tips

  • Explain why it matters in one sentence: identity checks are fast and safe.
  • Show the nested update path and point out which branches are shared.
  • List the non-mutating array methods from ES2023.