Sub topic 16
Practical Patterns: Immutable Updates and Omitting Keys
This chapter assumes you already know object and array spread, rest properties in patterns, parameter destructuring with defaults, and why spread copies are shallow. The patterns here combine those pieces into idioms you will see in UI state management, reducers, configuration handling, and API code. Each pattern answers one question: how do I produce a changed version of some data without touching the original?
An immutable update builds a new value that holds the change and leaves the original as it was. JavaScript objects are mutable by default, so immutability is a discipline you follow. The language does not enforce it. Spread and rest make that discipline short enough to use every day.
Why Immutable Updates Matter
Many tools detect change by comparing references with ===. React decides whether to re-render by checking whether state objects are new. Memoization caches compare inputs by reference. Redux-style reducers depend on old state staying intact, which is what makes time-travel debugging possible. If you mutate an object in place, its reference stays the same, and these tools conclude that nothing changed.
const state = { count: 1 };
const mutated = state;
mutated.count = 2;
console.log(mutated === state); // true: looks unchanged to a reference check
const copied = { ...state, count: 3 };
console.log(copied === state); // false: a change is detectableUpdating Nested Objects: Spread at Every Level You Change
Spread copies one level, so a nested update needs a new object at every level along the path to the change. Levels off that path can be reused as they are. This is called structural sharing: the new value shares unchanged branches with the old one.
const state = {
user: { name: 'Ada', address: { city: 'London', zip: 'N1' } },
settings: { theme: 'light' },
};
const moved = {
...state,
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' },
},
};
console.log(state.user.address.city); // 'London'
console.log(moved.user.address.city); // 'Paris'
console.log(moved.settings === state.settings); // true: shared, untouched branch
console.log(moved.user === state.user); // false: on the changed pathA common mistake is to stop spreading one level too early:
const state = { user: { name: 'Ada', address: { city: 'London' } } };
const wrong = { ...state, user: { ...state.user } };
wrong.user.address.city = 'Paris';
console.log(state.user.address.city); // 'Paris': the original was mutatedHere wrong.user is a new object, but wrong.user.address is still the original address. You need a new object at every level you modify.
Immutable Array Updates
Arrays need the same care. Methods such as push, splice, sort, and reverse mutate in place. The table maps each common operation to a non-mutating form.
| Operation | Mutating | Immutable alternative |
|---|---|---|
| Append | `arr.push(x)` | `[...arr, x]` |
| Prepend | `arr.unshift(x)` | `[x, ...arr]` |
| Remove by index | `arr.splice(i, 1)` | `arr.filter((_, j) => j !== i)` or `arr.toSpliced(i, 1)` |
| Insert at index | `arr.splice(i, 0, x)` | `[...arr.slice(0, i), x, ...arr.slice(i)]` |
| Replace at index | `arr[i] = x` | `arr.with(i, x)` or `arr.map((v, j) => j === i ? x : v)` |
| Sort | `arr.sort()` | `[...arr].sort()` or `arr.toSorted()` |
The toSorted, toSpliced, and with methods arrived in ES2023 and run in current browsers and Node.js 20 and later.
Arrays of objects are where the shallow-copy problem usually bites. To update one item, map over the array and spread only the item that matches:
const todos = [
{ id: 1, text: 'Write tests', done: false },
{ id: 2, text: 'Ship', done: false },
];
const toggled = todos.map((todo) =>
todo.id === 2 ? { ...todo, done: !todo.done } : todo
);
console.log(todos[1].done); // false
console.log(toggled[1].done); // true
console.log(toggled[0] === todos[0]); // true: unchanged item is reusedOmitting Keys with Rest Properties
To make a copy that leaves out some keys, destructure those keys and collect everything else with a rest property. This is the usual way to strip sensitive or internal fields before you send or log an object.
const account = { id: 42, email: '[email protected]', passwordHash: 'x9f...', role: 'admin' };
const { passwordHash, ...safeAccount } = account;
console.log(safeAccount); // { id: 42, email: '[email protected]', role: 'admin' }The variable passwordHash still exists after this line. Linters may report it as unused. Many teams turn off that warning for rest siblings (ESLint's no-unused-vars has an ignoreRestSiblings option), or they rename the binding to _ to show it is thrown away.
When the key is only known at runtime, use a computed property name in the pattern:
function omit(obj, key) {
const { [key]: _omitted, ...rest } = obj;
return rest;
}
console.log(omit({ a: 1, b: 2, c: 3 }, 'b')); // { a: 1, c: 3 }To omit several keys, a loop or Object.fromEntries reads better than chaining patterns:
function omitMany(obj, keys) {
const drop = new Set(keys);
return Object.fromEntries(Object.entries(obj).filter(([k]) => !drop.has(k)));
}
console.log(omitMany({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { b: 2 }Keep in mind that a rest property collects only own enumerable properties. Prototype methods and class getters are left out, so omit called on a class instance returns a plain object. That object is no longer an instance of the class.
Conditional Properties and Elements
Object spread skips null, undefined, false, and other primitives with no own enumerable properties. That lets you add a property only when a condition is true:
function buildQuery({ search, page, includeArchived }) {
return {
page: page ?? 1,
...(search && { q: search }),
...(includeArchived ? { archived: true } : {}),
};
}
console.log(buildQuery({ page: 2 })); // { page: 2 }
console.log(buildQuery({ search: 'js', includeArchived: true }));
// { page: 1, q: 'js', archived: true }Watch out with &&. If search is the empty string, search && {...} gives '', and spreading '' adds nothing, which is what you want. If the left side could be a non-empty string, though, spreading that string into an object adds index keys like 0, 1, and so on. Use the ternary form when the condition is not a plain boolean.
Array spread is stricter. Spreading false or undefined into an array literal throws a TypeError because those values are not iterable, so always fall back to an empty array:
const isAdmin = false;
const menu = ['Home', 'Profile', ...(isAdmin ? ['Admin'] : [])];
console.log(menu); // ['Home', 'Profile']Merging Options with Defaults
Earlier chapters showed per-property defaults in parameter patterns. When an options object is large, or you need to pass it on intact, merge it with a defaults object instead:
const DEFAULTS = Object.freeze({ retries: 3, timeout: 5000, headers: { accept: 'application/json' } });
function request(url, options = {}) {
const config = {
...DEFAULTS,
...options,
headers: { ...DEFAULTS.headers, ...options.headers },
};
return { url, ...config };
}
console.log(request('/api', { timeout: 1000, headers: { auth: 't0k' } }));
// { url: '/api', retries: 3, timeout: 1000,
// headers: { accept: 'application/json', auth: 't0k' } }Without the explicit headers line, the caller's headers object would replace the default headers completely, because spread merges only at the top level. Spreading options.headers when it is undefined is safe in an object literal.
Unlike per-property defaults in a pattern, the spread merge lets an explicit undefined override a default: request('/api', { timeout: undefined }) produces timeout: undefined. If that matters, filter out undefined values first, or use the parameter-pattern defaults, which apply only to undefined.
Choosing a Pattern
| Goal | Pattern |
|---|---|
| Change one nested field | Spread every level along the path |
| Update one item in an array | `map` with spread on the matching item |
| Remove a known key | `const { key, ...rest } = obj` |
| Remove a dynamic key | `const { [key]: _, ...rest } = obj` |
| Add a property conditionally | `...(cond ? { k: v } : {})` |
| Merge options with defaults | Spread defaults, then options, re-merging nested objects |
| Fully independent copy | `structuredClone(obj)` |
Exercise
Given const state = { items: [{ id: 1, qty: 1 }, { id: 2, qty: 5 }], total: 6 };, write one expression that returns a new state where item 2 has qty: 6 and total is 7, without mutating state. Which objects in the result are shared with the original?
Show answer
({ ...state, total: 7, items: state.items.map((it) => it.id === 2 ? { ...it, qty: 6 } : it) }). The root object, the items array, and item 2 are new. Item 1 ({ id: 1, qty: 1 }) is the same object in both states.
Exercise
What does const { [k]: _, ...rest } = { a: 1, b: 2 }; produce when k is 'z', and what is _?
Show answer
rest is { a: 1, b: 2 }, a new object holding every property because none matched 'z', and _ is undefined. Omitting a missing key does not throw.
Exercise
Why does const tags = [...(user.isVip && ['vip'])]; throw for a non-VIP user while { ...(user.isVip && { vip: true }) } does not?
Show answer
For a non-VIP user the expression evaluates to false. Array spread requires an iterable, and false is not iterable, so it throws a TypeError. Object spread ignores primitives such as false that have no own enumerable properties. Use ...(user.isVip ? ['vip'] : []) in the array.