Spread & Rest Operators

📚 Lesson 15 of 22  •  ⏱ 9 min read  •  Intermediate

Spread — Expand Iterables

JavaScript
// Copy an array (not a reference)
const original = [1, 2, 3];
const copy = [...original];  // new array, changes don't affect original

// Merge arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];  // [1, 2, 3, 4]
const withExtra = [...a, 99, ...b];  // [1, 2, 99, 3, 4]

// Spread into function arguments
const nums = [5, 2, 8, 1];
Math.max(...nums)  // 8 (instead of Math.max.apply(null, nums))
Math.min(...nums)  // 1

Spread with Objects

JavaScript
// Copy object (shallow)
const user = { name: "Priya", age: 22 };
const copy = { ...user };

// Merge objects (later values win)
const defaults = { theme: "dark", lang: "en", fontSize: 16 };
const prefs    = { lang: "ta", fontSize: 18 };
const settings = { ...defaults, ...prefs };
// { theme:"dark", lang:"ta", fontSize:18 }

// Add/override specific properties
const updatedUser = { ...user, age: 23, verified: true };
// original user unchanged

Rest — Collect Remaining

JavaScript
// Rest in function parameters — collect extra args
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4)  // 10

// Rest must be last parameter
function log(level, ...messages) {
  messages.forEach(msg => console.log(`[${level}]`, msg));
}
log("INFO", "Server started", "Port 3000");

Rest in Destructuring

JavaScript
// Array rest
const [first, second, ...remaining] = [10, 20, 30, 40, 50];
// first=10, second=20, remaining=[30,40,50]

// Object rest — get some properties, collect the rest
const { id, password, ...publicInfo } = user;
// Useful for removing sensitive fields before sending
sendToClient(publicInfo);  // no id or password

Spread vs Rest — Same Syntax, Different Uses

Reference
SPREAD — expands something into individual items
  [...array]     in array literal or function call
  {...object}    in object literal

REST — collects individual items into one thing
  function(...args)   in function definition
  [a, ...rest] = arr  in destructuring
  {x, ...rest} = obj  in destructuring