Understanding Spread and Rest Operators in JavaScript
In JavaScript, you’ll often see three dots ....
At first, it looks confusing, but it actually does two simple things depending on where it is used.
Spread → expands values
Rest → collects values
Same syntax, different purpose.
What Spread Operator Does
The spread operator expands elements.
Think of it as taking something grouped and spreading it out.
Example with array:
let arr = [1, 2, 3]
let newArr = [...arr]
console.log(newArr)
Here:
- values are copied and expanded into a new array
Using Spread with Arrays
You can also combine arrays easily:
let arr1 = [1, 2]
let arr2 = [3, 4]
let combined = [...arr1, ...arr2]
console.log(combined)
Result:
[1, 2, 3, 4]
Using Spread with Objects
Spread also works with objects:
let user = { name: "Ishan" }
let updatedUser = { ...user, age: 21 }
console.log(updatedUser)
This is useful for:
copying objects
updating values
What Rest Operator Does
The rest operator collects values into a group.
Example:
function sum(...numbers) {
console.log(numbers)
}
sum(1, 2, 3, 4)
Here:
- all values are collected into
numbersarray
Spread vs Rest (Key Difference)
This is where most people get confused.
Spread → expands values
Rest → collects values
Example:
let arr = [1, 2, 3]
function print(a, b, c) {
console.log(a, b, c)
}
print(...arr) // spread
function print(...values) {
console.log(values)
}
print(1, 2, 3) // rest
Practical Use Cases
Spread:
copying arrays
merging arrays
copying objects
Rest:
handling multiple arguments
grouping remaining values
Example:
let numbers = [1, 2, 3]
let copy = [...numbers]
function logAll(...items) {
console.log(items)
}
One Simple Way to Think
Spread → break things apart
Rest → gather things together
Conclusion
The spread and rest operators look the same, but their behavior depends on how they are used.
Once you understand:
spread = expand
rest = collect
most confusion disappears.