The rest parameter (...) allows a function to accept any number of arguments and collect them into a single array, making functions more flexible and dynamic.
- Represented using three dots (...) followed by a parameter name
- Collects multiple arguments into an array
- Must always be the last parameter in a function
- Useful for handling variable or unknown numbers of arguments
- Simplifies function definitions compared to the arguments object
function addNumbers(...numbers) {
let sum = 0;
for (let num of numbers) {
sum += num;
}
return sum;
}
console.log(addNumbers(1, 2));
console.log(addNumbers(1, 2, 3, 4));
Syntax
//... is the rest parameter (triple dots)
function functionname(...parameters)
{
statement;
}Note: When ... is at the end of the function parameter, it is the rest parameter. It stores n number of parameters as an array. Let's see how the rest parameter works:
Understanding How the Rest Parameter Works
[Example 1]: Without Using the Rest Parameter
Javascript code demonstrating the passing arguments more than the parameters without using rest parameter.
function fun(a, b){
return a + b;
}
console.log(fun(1, 2)); // 3
console.log(fun(1, 2, 3, 4, 5)); // 3
- Extra arguments beyond parameters are ignored without error.
- Use ... to collect additional arguments into an array.
- Rest parameters allow flexible argument handling for functions.
[Example 2]: Using the Rest Parameter
JavaScript code demonstrating the addition of numbers using the rest parameter.
// es6 rest parameter
function fun(...input) {
let sum = 0;
for (let i of input) {
sum += i;
}
return sum;
}
console.log(fun(1, 2)); //3
console.log(fun(1, 2, 3)); //6
console.log(fun(1, 2, 3, 4, 5)); //15
We can calculate the sum of all arguments passed to the fun() function by iterating over them as an array using the for..of loop.
- The rest parameter collects all arguments into an array.
- The for..of loop traverses each element and adds it to the sum.
Note: The rest parameter must be the last argument because it gathers all remaining values into an array; placing any parameter after it causes a syntax error.
[Example 3]: Using Rest Parameter with Other Parameters
In this example, we are using the rest parameter with some other arguments inside a function.
// rest with function and other arguments
function fun(a, b, ...c) {
console.log(`${a} ${b}`); //Mukul Latiyan
console.log(c); //[ 'Lionel', 'Messi', 'Barcelona' ]
console.log(c[0]); //Lionel
console.log(c.length); //3
console.log(c.indexOf('Lionel')); //0
}
fun('Mukul', 'Latiyan', 'Lionel', 'Messi', 'Barcelona');
- The rest parameter collects extra arguments into an array, handling more than the defined parameters.
- In the function, c[0] returns 'Lionel' from the rest parameter array.
- The rest parameter is an array, allowing use of standard array methods for further manipulation.