Coding Techniques
Spread and Rest Operators · Study material
Spread vs Object.assign
Both copy own enumerable properties, but Object.assign assigns into an existing target (running its setters and mutating it), while spread defines properties on a brand-new object:
// Object.assign WRITES into its target (running setters); spread always creates a fresh object
const target = {
set price(v) { this._price = Math.round(v); },
};
Object.assign(target, { price: 99.6 });
const spreadCopy = { ...target, price: 99.6 };
console.log(target._price, Object.keys(target));
console.log(spreadCopy.price, Object.keys(spreadCopy));
100 [ 'price', '_price' ] 99.6 [ 'price', '_price' ]
Immutable array operations
Insert, remove, replace and toggle without mutating the original – the patterns behind every React list update:
const list = ["a", "b", "c", "d"];
const insertAt = (arr, i, item) => [...arr.slice(0, i), item, ...arr.slice(i)];
const removeAt = (arr, i) => [...arr.slice(0, i), ...arr.slice(i + 1)];
const replaceAt = (arr, i, item) => arr.map((x, j) => (j === i ? item : x));
const toggle = (arr, item) => (arr.includes(item) ? arr.filter((x) => x !== item) : [...arr, item]);
console.log(insertAt(list, 2, "X"), removeAt(list, 1));
console.log(replaceAt(list, 0, "Z"), toggle(list, "c"), toggle(list, "e"));
console.log(list); // never changed
[ 'a', 'b', 'X', 'c', 'd' ] [ 'a', 'c', 'd' ] [ 'Z', 'b', 'c', 'd' ] [ 'a', 'b', 'd' ] [ 'a', 'b', 'c', 'd', 'e' ] [ 'a', 'b', 'c', 'd' ]
Spread and rest at a glance
| Goal | Code |
|---|---|
| Copy an array / object | [...arr] / { ...obj } |
| Merge with overrides | { ...defaults, ...options } |
| Add a property only if | { ...(ok && { k: v }) } |
| Array as arguments | Math.max(...nums) |
| Unique values | [...new Set(arr)] |
| Any number of arguments | function f(...args) |
| Remove a field | const { pw, ...safe } = user |
| Update nested state | { ...s, user: { ...s.user, name } } |
Spread and rest checklist
- Put defaults first and overrides last when merging.
- Strip undefined values before merging if they should not override defaults.
- Spread every changed level in nested updates.
- Guard optional arrays before spreading: [...(list ?? [])].
- Use rest parameters instead of arguments.
- Do not spread very large arrays into function calls.