The spread and rest operators both use the ... syntax in JavaScript, but they behave differently based on context. Spread expands values, while rest collects values. These features make working with arrays, objects, and functions much more flexible and expressive.
...) but serve opposite purposes depending on where they are used.[...array], { ...object }, fn(...argsArray)function fn(...params) {} – collects all remaining arguments in one array.const [first, ...rest] = arr;const { key, ...restObj } = obj;The spread operator expands an iterable into individual elements. It is commonly used for copying, merging, and passing array values into functions.
// Spread in arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
// Spread in objects
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
// Spread in function calls
const nums = [10, 20, 30];
console.log(Math.max(...nums)); // 30
The rest operator groups multiple elements into a single array. It appears in function parameters and destructuring assignments, helping you handle “the rest” of the data in a clean way.
// Rest in function parameters
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Rest in array destructuring
const [first, ...restArr] = [10, 20, 30, 40];
console.log(first); // 10
console.log(restArr); // [20, 30, 40]
// Rest in object destructuring
const { a, ...restObj } = { a: 1, b: 2, c: 3 };
console.log(a); // 1
console.log(restObj); // { b: 2, c: 3 }
... syntax but behave differently depending on context.arr2 becomes [1, 2, 3, 4, 5] because we spread arr1 and add extra values.obj2 becomes { a: 1, b: 2, c: 3 } – a shallow copy of obj1 with one more property.Math.max(...nums) passes 10, 20, 30 as separate arguments and returns 30.sum(1, 2, 3, 4) uses rest to collect all arguments into numbers and returns their total: 10.10 in first and the remaining values in restArr.1 in a and the remaining properties in restObj.Set.arguments object to instead use rest parameters.