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:
Contribute to Docs
- 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.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours