What is the spread operator and rest parameters?
Both use the same ... syntax but do opposite things, depending on where they appear.
Spread — expands an array or object into individual items: copying arrays, merging objects, or passing array items as arguments.
Rest — collects multiple remaining items into a single array: gathering leftover function arguments or destructured values.
Memory aid: spread spreads a collection out; rest gathers the rest in. Spread is also the simplest way to make a shallow copy.
// Spread in arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
const copy = [...arr1]; // Shallow copy
const withNew = [...arr1, 4]; // [1, 2, 3, 4]
// Spread in objects
const defaults = { color: 'red', size: 'M' };
const custom = { color: 'blue', weight: 5 };
const merged2 = { ...defaults, ...custom };
// { color: 'blue', size: 'M', weight: 5 } — last wins
// Spread in function calls
const nums = [1, 5, 3, 9, 2];
console.log(Math.max(...nums)); // 9 (spreads array as arguments)
// Rest parameters (function)
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Rest in destructuring
const [first, ...remaining] = [1, 2, 3, 4];
console.log(remaining); // [2, 3, 4]
const { id, ...userData } = { id: 1, name: 'John', email: 'j@t.com' };
console.log(userData); // { name: 'John', email: 'j@t.com' }Spread expands: [...arr] copies an array, {...obj} copies an object, Math.max(...nums) passes array as arguments, {...a, ...b} merges objects (last wins for conflicts). Rest collects: ...numbers in function gathers all arguments into an array, ...remaining in destructuring collects leftover elements.
Both use ... but context determines the behavior.
Context determines behavior: ... in definition = rest (collects), ... in usage = spread (expands). The shallow copy limitation is important.
Object merge with last-wins for conflicts. Math.max(...array) is the classic spread example.