Sub topic 16
Practical Patterns: Immutable Updates and Omitting Keys
This chapter assumes you already know object and array spread, rest properties, and why spread copies are shallow. It combines those pieces into patterns that show up often in state management, API handling, and configuration code.
Immutable Updates, One Level at a Time
An immutable update builds a new object instead of changing the old one. Code that holds the original, such as a UI framework comparing old and new state, can then detect the change by checking whether the reference is the same.
Spread copies only one level, so you must spread at every level you change. Levels you don't change are reused by reference. This sharing is intended, and it is what keeps the update cheap.
const state = {
user: { name: 'Ada', prefs: { theme: 'light', lang: 'en' } },
token: 'abc'
};
const next = {
...state,
user: {
...state.user,
prefs: { ...state.user.prefs, theme: 'dark' }
}
};
console.log(state.user.prefs.theme); // 'light' (original untouched)
console.log(next.user.prefs.theme); // 'dark'
console.log(next.token === state.token); // true (unchanged values reused)
console.log(next.user !== state.user); // true (changed path is new)Immutable Array Updates
Arrays follow the same rule. Use spread and non-mutating methods instead of push, splice, or index assignment.
const todos = [
{ id: 1, done: false },
{ id: 2, done: false }
];
const added = [...todos, { id: 3, done: false }];
const toggled = todos.map(t => (t.id === 2 ? { ...t, done: true } : t));
const removed = todos.filter(t => t.id !== 1);
console.log(todos.length, added.length); // 2 3
console.log(todos[1].done, toggled[1].done); // false true
console.log(removed.map(t => t.id)); // [2]Omitting Keys with Rest Properties
To copy an object without some keys, destructure those keys out and keep the rest. This works well for removing secrets before sending data to a client.
const account = { id: 7, email: '[email protected]', password: 'hunter2' };
const { password, ...safeAccount } = account;
console.log(safeAccount); // { id: 7, email: '[email protected]' }When the key to remove 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 }Options Objects with Pass-Through
Parameter destructuring and rest combine well. Pull out the options your function handles and pass the rest to another function unchanged.
function request(url, { retries = 3, ...fetchOptions } = {}) {
return { url, retries, fetchOptions };
}
console.log(request('/api', { retries: 1, method: 'POST' }));
// { url: '/api', retries: 1, fetchOptions: { method: 'POST' } }Exercise
Given const cart = { items: [{ sku: 'A', qty: 1 }], coupon: 'SAVE' };, write one expression that returns a new cart where item 'A' has qty 2 and coupon is removed, without mutating cart.
Show answer
(({ coupon, ...rest }) => ({ ...rest, items: rest.items.map(i => (i.sku === 'A' ? { ...i, qty: 2 } : i)) }))(cart). The rest property drops coupon, map builds a new items array, and spreading the matching item copies it before qty changes.
Exercise
After const next = { ...state, user: { ...state.user } };, is next.user.prefs === state.user.prefs true or false, and why?
Show answer
True. Spreading state.user copies only its top-level properties, so prefs is still the same object reference in both.