Sub topic 6
Working Without Mutation
This chapter assumes you know object and array literals, spread syntax (...), and the idea that objects in JavaScript are passed by reference. It builds on the previous chapters about pure functions and side effects.
Why mutation causes trouble
To mutate a value is to change it in place. Objects and arrays are shared by reference, so a change made through one variable is visible through every other variable that points to the same value. A function that mutates its argument has a side effect, even if it looks like a simple helper.
const cart = { items: ['apple'] };
const saved = cart; // same object, not a copy
function addItem(c, item) {
c.items.push(item); // mutates the caller's object
return c;
}
addItem(cart, 'pear');
console.log(saved.items); // [ 'apple', 'pear' ] (changed too)When you work without mutation, you stop changing existing values. You create new ones that hold the update. The original stays as it was, so any code still holding it can rely on it.
Copying with spread and non-mutating methods
Spread syntax builds a new object or array from an existing one. You can override fields as you copy.
const user = { name: 'Ada', tags: ['math'] };
const renamed = { ...user, name: 'Grace' };
const tagged = { ...user, tags: [...user.tags, 'code'] };
const nums = [3, 1, 2];
const sorted = nums.toSorted((a, b) => a - b); // ES2023, does not mutate
console.log(user.name, user.tags.length); // Ada 1
console.log(renamed.name, tagged.tags); // Grace [ 'math', 'code' ]
console.log(nums, sorted); // [ 3, 1, 2 ] [ 1, 2, 3 ]Many array methods mutate. ES2023 added copying versions of them (Node 20+ and current browsers):
| Mutating | Non-mutating alternative |
|---|---|
| `arr.push(x)` | `[...arr, x]` |
| `arr.sort(fn)` | `arr.toSorted(fn)` |
| `arr.reverse()` | `arr.toReversed()` |
| `arr.splice(i, 1)` | `arr.toSpliced(i, 1)` |
| `arr[i] = x` | `arr.with(i, x)` |
Common errors
Shallow copies share nested values
Spread copies only one level. Nested objects and arrays are still shared.
const user = { name: 'Ada', tags: ['math'] };
const copy = { ...user };
copy.tags.push('code');
console.log(user.tags); // [ 'math', 'code' ] (original changed)To fix this, copy every level you change, as tagged does above. If you need a full independent copy, use structuredClone(user). It cannot clone functions.
Object.freeze is shallow and can fail silently
Object.freeze blocks changes to an object's own properties. It does not freeze nested objects. In sloppy (non-strict) mode, assigning to a frozen property fails without any error. In strict mode, and in ES modules, the assignment throws a TypeError.
'use strict';
const config = Object.freeze({ port: 80, hosts: ['a'] });
config.hosts.push('b'); // allowed: nested array is not frozen
console.log(config.hosts); // [ 'a', 'b' ]
try {
config.port = 8080;
} catch (e) {
console.log(e instanceof TypeError); // true
}`const` does not mean immutable
const stops you from reassigning the variable. You can still change the object it holds.
Exercise
Rewrite function addItem(c, item) { c.items.push(item); return c; } so it returns an updated cart and leaves the original cart and its items array unchanged.
Show answer
const addItem = (c, item) => ({ ...c, items: [...c.items, item] }); The outer spread copies the cart and the inner spread copies the array, so neither the original object nor its nested array is modified.
Exercise
Given const scores = [50, 90, 70];, how do you get a copy with the second score replaced by 95 and a descending sorted copy, without changing scores?
Show answer
const updated = scores.with(1, 95); gives [50, 95, 70], and const desc = scores.toSorted((a, b) => b - a); gives [90, 70, 50]. scores stays [50, 90, 70].