In JavaScript, both the spread and rest operators use the same syntax ... but they serve different purposes depending on the context.
πΉ Spread Operator (...)
The spread operator is used to expand (spread out) elements of an iterable (like an array, string, or object) into individual elements.
β Examples:
- Array Expansion
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]
- Object Expansion
const obj1 = {a: 1, b: 2};
const obj2 = {...obj1, c: 3};
console.log(obj2); // {a: 1, b: 2, c: 3}
- Function Arguments
function sum(a, b, c) {
return a + b + c;
}
const nums = [1, 2, 3];
console.log(sum(...nums)); // 6
π Spread is about unpacking data.
πΉ Rest Operator (...)
The rest operator is used to collect (gather) multiple elements into a single array/object.
β Examples:
- Function Parameters
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
- Object Destructuring
const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4};
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}
- Array Destructuring
const [first, ...others] = [10, 20, 30, 40];
console.log(first); // 10
console.log(others); // [20, 30, 40]
π Rest is about packing data.
π― Key Difference
- Spread (
...) β Expands elements (unpacks). - Rest (
...) β Collects elements (packs).
β‘Quick way to remember:
π Spread = Expand
π Rest = Collect/Condense
