Spread vs Rest Operators in JavaScript

In JavaScript, the spread operator (...) and the rest operator (...) look the same, but they do opposite jobs. Once you understand them as expanding vs collecting, they become very easy.
What the Spread Operator does
The spread operator expands or spreads elements from an array or object.
Think of it like:
“Open up and spread everything out”
Example with arrays
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
//output: [1, 2, 3, 4, 5]
Here, ...numbers spreads all values into a new array.
Example with objects
const user = { name: "piyush", age: 25 };
const updatedUser = { ...user, city: "Kolkata" };
console.log(updatedUser);
//output;- { name: "piyush", age: 25, city: "Kolkata" }
Real-world use cases of Spread
1. Copying arrays or objects
const arrCopy = [...arr];
const objCopy = { ...obj };
2. Merging arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
3. Updating objects
const updatedUser = { ...user, age: 26 };
What the Rest Operator does
The rest operator collects remaining values into a single array or object.
Think of it like:
“Gather everything left into one group”
Example with function arguments
function sum(...numbers) {
console.log(numbers);
}
sum(1, 2, 3, 4);
//output: [1, 2, 3, 4]
Here, ...numbers collects all arguments into an array.
Example with arrays
const [first, ...rest] = [10, 20, 30, 40];
console.log(first);
console.log(rest);
//output: 10
//[20, 30, 40]
Real-world use cases of Rest
1. Handling unknown number of function arguments
function logAll(...items) {
items.forEach(item => console.log(item));
}
2. Splitting values
const [head, ...tail] = [1, 2, 3, 4];
Differences between spread and rest
| Feature | Spread | Rest |
|---|---|---|
| Meaning | Expands values | Collects values |
| Used for | Arrays, objects, function calls | Function parameters, destructuring |
| Result | Breaks items apart | Groups items together |
Simple way to remember:
Spread = expands (breaks apart)
Rest = collects (puts together)
Practical Everyday Uses
Copying data safely (no mutation)
const copy = [...originalArray];
Combining data sources
const allUsers = [...admins, ...customers];
Flexible functions
function multiply(multiplier, ...nums) {
return nums.map(n => n * multiplier);
}
Final Summary
Spread (
...) → expands values outRest (
...) → collects values inSame syntax, different context
If you understand this one idea—expand vs collect—you’ve basically mastered both operators.




