Rest Operator in JavaScript
Florian Olivo on Unsplash
What is Rest Operator?
The rest operator in JavaScript, denoted by three dots (...), allows you to represent an indefinite number of arguments as an array within a function. It's called the "rest" operator because it gathers up the remaining arguments into a single array "rest" parameter.
function sum(...numbers) {
let result = 0;
for (let number of numbers) {
result += number;
}
return result;
}
console.log(sum(1, 2)); // Output: 3
console.log(sum(1, 2, 3, 4)); // Output: 10
console.log(sum(5, 10, 15)); // Output: 30In this example, the sum function takes an indefinite number of arguments using the rest parameter syntax ...numbers. This syntax collects all the arguments passed to the sum function into an array called numbers.
When you call sum(1, 2), numbers will be [1, 2], so the function returns the sum of those numbers, which is 3.
Similarly, when you call sum(1, 2, 3, 4), numbers will be [1, 2, 3, 4], so the function returns the sum of all these numbers, which is 10.
And when you call sum(5, 10, 15), numbers will be [5, 10, 15], so the function returns the sum of these numbers, which is 30.
Get Saravanan Software Programmer’s stories in your inbox
Join Medium for free to get updates from this writer.
In each case, the rest operator (...) gathers up all the arguments passed to the function and stores them in the numbers array, allowing you to work with them as a collection.
Added Information:
Before the introduction of the rest parameter syntax, JavaScript provided the arguments object inside every function, which behaves similarly to the rest parameter.
The arguments object is an array-like object that holds all the arguments passed to the function. However, unlike the rest parameter, it's not an actual array, so you can't use array methods directly on it.
Here’s an example using arguments:
function sum() {
let result = 0;
for (let i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
console.log(sum(1, 2)); // Output: 3
console.log(sum(1, 2, 3, 4)); // Output: 10
console.log(sum(5, 10, 15)); // Output: 30In this example, arguments holds all the arguments passed to the sum function, allowing you to loop through them and calculate the sum.
However, the rest parameter syntax is generally preferred because it’s more explicit and behaves like a real array, making it easier to work with the arguments.
Thanks for reading! 🕊️ I hope you found this explanation of the rest operator in JavaScript helpful. Happy coding! ✌️.









