Spread vs Rest Operators
What Spread Operator Does?
The spread operator is used to expand (unpack) values.
It takes elements from an array/object and spreads them out.
Example with Arrays:
const nums = [1, 2, 3];
const newNums = [...nums, 4, 5];
console.log(newNums); // [1, 2, 3, 4, 5]
It “opens up” the array.
Example with Objects
const user = { name: "Ayush", age: 20 };
const updatedUser = { ...user, city: "Kolkata" };
console.log(updatedUser);//{ name: "Ayush", age: 20, city: "Kolkata" }
What Rest Operator Does
The rest operator is used to collect values into one variable.
It gathers multiple values into an array.
Example in Function:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
All arguments → collected into numbers
Example with Arrays:
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
Difference Between Spread and Rest
| Feature | Spread (...) |
Rest (...) |
|---|---|---|
| Purpose | Expand values | Collect values |
| Direction | Inside → Outside | Outside → Inside |
| Usage | Arrays, objects, function calls | Function params, destructuring |
Conclusion
The spread and rest operators might seem same but function differently while using in place of code.