Rest Parameters
Rest parameters are a form of parameter tied to an array, which allows for the concise introduction of a variable number of terms in a function call. This is also called a variadic function. In JavaScript a variadic function can be created and called to accept an indefinite number of arguments by utilizing the rest parameter syntax ...
.
Syntax
function functionName(...parameterName) {
statements;
}
The function should follow the same declaration syntax with the addition of the ...
operator prefixing the parameter name. Each value will be applied separately to the function body.
Example
The following code demonstrates a basic implementation of a rest parameter:
function sumVals(...vals) {let total = 0;for (let val of vals) {total += val;}return total;}let nums = [2, 4, 6, 8, 10];console.log(sumVals(...nums));
The above example will return the following result:
30
Alternatively, other values can be included to supplement the values in the array, as in the following code:
console.log(sumVals(...nums, 10));
Which yields:
40
Codebyte Example
The following codebyte example creates the function getUsers
to simulate a response.status
. Each status returns a different message and for this, the ...
rest operator is used to pass all the possible messages that can be presented. All the messages are grouped into the param
array and later selected to appear in the output:
All contributors
- davialano1 total contribution
- CaupolicanDiaz142 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.