Both use the same syntax (...) but behave differently depending on where they are used.
β
1. Spread Operator (...)
π Expands / spreads values OUT
Used to unpack arrays, objects, or function arguments.
πΉ Use Cases of Spread
β A. Copying an array
const arr = [1, 2, 3];
const copy = [...arr];
β B. Merging arrays
const nums = [...arr1, ...arr2];
β C. Copying an object
const userCopy = { ...user };
β D. Sending array values as function arguments
Math.max(...[4, 1, 9]); // 9
π§ Spread = EXPAND
β
2. Rest Operator (...)
π Collects values IN
Used to gather remaining items into an array or object.
πΉ Use Cases of Rest
β A. Function parameters
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
β B. Destructuring arrays
const [first, ...rest] = [1, 2, 3, 4];
console.log(rest); // [2,3,4]
β C. Destructuring objects
const { id, ...details } = { id: 1, name: "Teekam", age: 26 };
console.log(details); // { name: "Teekam", age: 26 }
π§ Rest = COLLECT
π₯ Key Difference Summary
| Operator | Meaning | Usage | Example |
|---|---|---|---|
| Spread | Expands | Copy, merge, pass arguments | ...[1,2,3] |
| Rest | Collects | Function parameters, destructuring | ...nums in function(...nums) |
π― Short Interview Answer
Spread operator expands values into individual elements, while Rest operator collects multiple values into a single array or object.
Spread is used for copying/merging, and Rest is used for handling variable arguments and destructuring.