The spread operator (...) and rest parameters (...) both use the same syntax (...),
but they serve opposite purposes — one expands values, and the other collects them.
1️⃣ Spread Operator — Expands Values
The spread operator is used to expand (or unpack) iterable values like arrays or objects.
🔹 Use in Arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5]
🔹 Use in Objects
const user = { name: "Teekam", age: 25 };
const updated = { ...user, country: "India" };
console.log(updated); // { name: "Teekam", age: 25, country: "India" }
🔹 Use in Function Calls
function sum(a, b, c) {
return a + b + c;
}
const nums = [1, 2, 3];
console.log(sum(...nums)); // 6
✅ Think: Spread breaks things apart.
2️⃣ Rest Parameters — Collects Values
The rest parameter collects multiple arguments into an array in function definitions.
🔹 Example
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
🔹 Destructuring Example
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
✅ Think: Rest gathers things together.
💡 In Short:
| Feature | Purpose | Example |
|---|---|---|
Spread (...) |
Expands arrays/objects | sum(...nums) |
Rest (...) |
Collects remaining values | function sum(...args) |
🔹 Spread = Expand
🔹 Rest = Gather