Spread & Rest Operators
📖 Concept
Both use ... syntax but serve opposite purposes:
Spread (...) EXPANDS an iterable into individual elements. Used in function calls, array literals, and object literals.
Rest (...) COLLECTS multiple elements into a single array. Used in function parameters and destructuring.
Rule of thumb: If ... appears on the LEFT side of = or in function parameters → it's Rest (collecting). If on the RIGHT side or in arguments/literals → it's Spread (expanding).
🏠 Real-world analogy: Spread is like unpacking a suitcase and laying everything out. Rest is like packing everything that's left into a suitcase.
💻 Code Example
1// SPREAD — expanding2const nums = [1, 2, 3];3const moreNums = [...nums, 4, 5]; // [1, 2, 3, 4, 5]4console.log(Math.max(...nums)); // 356// Spread for copies (shallow!)7const original = [1, [2, 3]];8const copy = [...original];9copy[1].push(4);10console.log(original[1]); // [2, 3, 4] ⚠️ Shallow copy!1112// Object spread13const defaults = { theme: "dark", lang: "en", debug: false };14const userPrefs = { theme: "light", debug: true };15const config = { ...defaults, ...userPrefs };16// { theme: "light", lang: "en", debug: true } — later spreads win1718// REST — collecting19function sum(...numbers) {20 return numbers.reduce((a, b) => a + b, 0);21}22console.log(sum(1, 2, 3, 4)); // 102324// Rest in destructuring25const [first, second, ...remaining] = [1, 2, 3, 4, 5];26console.log(remaining); // [3, 4, 5]2728const { name, ...otherProps } = { name: "Alice", age: 25, city: "NYC" };29console.log(otherProps); // { age: 25, city: "NYC" }3031// Real-world: removing a property immutably32const user = { id: 1, name: "Bob", password: "secret" };33const { password, ...safeUser } = user;34console.log(safeUser); // { id: 1, name: "Bob" } — password removed!3536// Combining with function params37function log(level, ...messages) {38 console.log(`[${level}]`, ...messages); // spread in function call39}40log("ERROR", "Server down", "Code: 500");
🏋️ Practice Exercise
Mini Exercise:
- Merge two arrays and remove duplicates using spread + Set
- Write a function with required first param and optional rest params
- Use object spread to create an immutable update pattern (update one field)
- Use rest + destructuring to separate the first item from an array in one line
⚠️ Common Mistakes
Spread creates a SHALLOW copy — nested objects/arrays are still references
Rest parameter must be the LAST parameter in a function definition
Can't use spread on non-iterables:
...123throws — only arrays, strings, Maps, Sets, etc.Order matters with object spread:
{ ...a, ...b }—b's properties overridea'sConfusing the
argumentsobject with rest parameters —argumentsis not a real array and doesn't work in arrow functions
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Spread & Rest Operators. Login to unlock this feature.