Spread vs Rest Operators in JavaScript

1. What is the Spread Operator (...)?
The Spread operator "expands" or "unpacks" an iterable (like an array or object) into individual elements.
Using Spread with Arrays and Objects
Arrays: It’s great for copying or merging arrays without mutating the original.
const parts = ['shoulders', 'knees'];
const body = ['head', ...parts, 'toes'];
// Result: ['head', 'shoulders', 'knees', 'toes']
Objects: It allows you to shallow-clone objects or update specific properties easily.
const user = { name: 'Diwya', role: 'Dev' };
const updatedUser = { ...user, role: 'Senior Dev' };
// Result: { name: 'Diwya', role: 'Senior Dev' }
2. The Rest Operator (...)
The Rest operator does the exact opposite: it "collects" multiple individual elements and bunches them into a single array. It is most commonly used in function parameters.
Function Arguments
If you don't know how many arguments a user will pass, "rest" handles it gracefully.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Result: 10
Destructuring
Pulling one property out of an object and keeping "the rest" together.
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
3. Key Differences: Spread vs. Rest
Feature | Spread Operator | Rest Operator |
Action | Expands (unpacks) elements. | Collects (packs) elements. |
Location | Used in array literals, object literals, or function calls. | Used in function parameters or destructuring patterns. |
Goal | To distribute values. | To condense multiple values into one variable. |
Direction | Inside → Outside | Outside → Inside |
Simple way to remember:
Spread = “Break things apart”
Rest = “Gather things together”
4. Expanding vs Collecting (Core Idea)
Spread (Expanding)
const nums = [1, 2, 3];
console.log(...nums); // 1 2 3
Rest (Collecting)
function demo(...args) {
console.log(args); // [1, 2, 3]
}
demo(1, 2, 3);
5. Real-World Use Cases
Copying Arrays (Immutable update)
const oldList = ["a", "b"];
const newList = [...oldList, "c"];
Merging Objects (React / State updates)
const state = { name: "Dev", age: 20 };
const newState = { ...state, age: 21 };
Function Arguments
const nums = [5, 10, 15];
Math.max(...nums); // 15
Flexible Functions
function logAll(...items) {
items.forEach(item => console.log(item));
}
Final Summary
...is the same syntax but behaves differently based on contextSpread → expands values
Rest → collects values
Widely used in:
React (state updates)
APIs (flexible arguments)
Clean & modern JS code






