Spread & Rest Operators (...)
The three dots ... do two related jobs: spread expands arrays/objects; rest collects remaining items. Both are everywhere in React (copy state) and Node (merge config).
Spread — copy & merge
const defaults = { theme: 'dark', lang: 'en' };
const userPrefs = { lang: 'hi', fontSize: 16 };
const settings = { ...defaults, ...userPrefs };
// { theme: 'dark', lang: 'hi', fontSize: 16 }
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
Rest — collect remaining
function sum(first, ...rest) {
return rest.reduce((total, n) => total + n, first);
}
sum(10, 5, 3, 2); // 20
const [leader, ...team] = ['Sandeep', 'Alex', 'Priya'];
// leader = 'Sandeep', team = ['Alex', 'Priya']
🌍 Real-world example — React-style state update (concept)
const cart = [{ id: 1, qty: 1 }];
function addToCart(cart, newItem) {
return [...cart, newItem]; // new array — do not mutate old
}
addToCart(cart, { id: 2, qty: 1 });
// cart unchanged; new array returned
React uses this idea: spread creates a new array/object so the UI knows something changed.
⚠️ Common Mistake: Mutating state directly:
cart.push(item) then expecting React to re-render. Use spread to return a new array.💡 Tip: Order matters when merging objects: later spreads overwrite earlier keys.
👨🏫 Teaching note: Show shallow copy vs reference: change nested object after spread — nested object is still shared. Deep clone needs other tools.