Spread vs Rest Operators in JavaScript
Same syntax (...), completely different purposes.

At first glance, both spread and rest use:
...
But they behave very differently depending on the context.
The Core Idea:
Spread โ Expands values ๐ค
Rest โ Collects values ๐ฅ
What is the Spread Operator?
The spread operator (...) is used to expand elements.
Example With Arrays:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2);
Visual:
[1, 2, 3]
โ (spread)
1, 2, 3
Spread With Objects
const user = { name: "Viraj", age: 24 };
const updatedUser = { ...user, city: "Pune" };
Visual:
{ name, age }
โ
{ name, age, city }
What is the Rest Operator?
The rest operator (...) is used to collect multiple values into one.
Example With Functions:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
sum(1, 2, 3, 4);
Visual:
1, 2, 3, 4
โ (rest)
[1, 2, 3, 4]
Rest Destructuring
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]
Spread vs Rest (Key Differences)
Feature | Spread | Rest
---------------|--------------------|-------------------
Purpose | Expand values | Collect values
Usage | Arrays, Objects | Function params, destructuring
Direction | Inside โ Outside | Outside โ Inside
Think Like This:
Spread = Unpack Things
Rest = Pack Things
Practical Use Cases
1. Copying Arrays
const arr = [1, 2, 3];
const copy = [...arr];
2. Merging Arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
3. Updating Objects (Immutable Way)
const user = { name: "Viraj", age: 24 };
const updated = { ...user, age: 25 };
4. Handling Multiple Arguments
function logAll(...args) {
console.log(args);
}
5. Removing Properties From Objects
const user = { name: "Viraj", age: 24, city: "Pune" };
const { city, ...rest } = user;
console.log(rest);
Real World Pattern
React Prop Example:
function Button({ title, ...props }) {
return <button {...props}>{title}</button>;
}
Very common in modern JavaScript frameworks.
Common Mistakes
Using Rest in Wrong Position
function test(...args, last) {} // โ Error
Rest must be last parameter
Confusing Spread with Rest
Same syntax โ Same behavior
Visual Summary
Spread โ Break apart values
Rest โ Gather values together
Key Takeways:
Same Syntax different meaning
Spread = expand , Rest = Collect
Widely used in modern JS
Important for interviews + real world apps




