Spread vs Rest Operators in JavaScript

When working with arrays, objects, and functions in JavaScript, you will often see this syntax: ...
This is used in two ways: the spread operator and the rest operator.
Even though they look the same, their behavior is completely different depending on where they are used.
Understanding the Core Idea
Spread expands values
Rest collects values
It's like :
- Spread breaks things apart, while rest groups things together.
What the Spread Operator Does
The spread operator expands elements.
Example with Arrays
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
// [1, 2, 3, 4, 5]
: the array is expanded into individual values.
Example with Objects
const user = {
name: "sam",
age: 22
};
const updatedUser = {
...user,
city: "Kolkata"
};
console.log(updatedUser);
All properties from user are copied into a new object.
Why Use Spread
Copy arrays or objects
Merge data
Avoid changing original values
What the Rest Operator Does
The rest operator collects values into an array.
Example with Function Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));
// 10
All arguments are grouped into the numbers array.
Example with Destructuring
const numbers = [1, 2, 3, 4];
const [first, ...rest] = numbers;
console.log(first); // 1
console.log(rest); // [2, 3, 4]
The rest operator collects remaining elements.
Differences Between Spread and Rest
| Feature | Spread | Rest |
|---|---|---|
| Purpose | Expands values | Collects values |
| Usage | Arrays, objects, and function calls | Parameters, destructuring |
| Direction | Inside to outside | Outside to inside |
Using Spread with Arrays and Objects
Copying Arrays
const arr1 = [1, 2];
const arr2 = [...arr1];
Merging Arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
Copying Objects
const user = { name: "Sam" };
const copy = { ...user };
Merging Objects
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = { ...obj1, ...obj2 };
If keys are the same, the last one overrides.
Practical Use Cases
Avoid Mutating Data
const original = [1, 2, 3];
const updated = [...original, 4];
Passing Array Values to Functions
const nums = [1, 2, 3];
Math.max(...nums);
Flexible Function Arguments
function logNames(...names) {
console.log(names);
}
logNames("A", "B", "C");
Extracting Values with Rest
const [first, ...others] = ["a", "b", "c"];
console.log(others);
// ["b", "c"]
Simple Visual
Spread:
[1, 2, 3] → ... → 1, 2, 3
Rest:
1, 2, 3 → ... → [1, 2, 3]
Conclusion
Spread and rest use the same syntax but do opposite things.
Spread expands values into individual elements.
Rest collects multiple values into a single array.
Once you understand this difference, working with arrays, objects, and functions becomes much easier.




