Last Updated : 11 Jul, 2025
The JavaScript Rest parameter allows a function to accept an indefinite number of arguments as an array. It is represented by three dots (...) followed by the parameter name and must be the last parameter in the function, enabling flexible and dynamic argument handling.
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:
Let's see how the rest parameter works.
Example 1: Without Using the Rest ParameterJavascript code demonstrating the passing arguments more than the parameters without using rest parameter
JavaScript
function fun(a, b){
return a + b;
}
console.log(fun(1, 2)); // 3
console.log(fun(1, 2, 3, 4, 5)); // 3
Explanation: In the above code example
JavaScript code demonstrating the addition of numbers using the rest parameter.
JavaScript
// 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 were able to get the sum of all the elements that we enter in the argument when we call the fun() function. We get the sum of all the elements in the array by making use of the for..of loop which is used to traverse the iterable elements inside an array.
Example 3: Using Rest Parameter with Other ParametersNote: The rest parameter has to be the last argument, as its job is to collect all the remaining arguments into an array. So having a function definition like the code below doesn't make any sense and will throw an error.
In this example, we are using the rest parameter with some other arguments inside a function.
javascript
// 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');
Mukul Latiyan [ 'Lionel', 'Messi', 'Barcelona' ] Lionel 3 0
Explanation:
We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4