Javascript's Rest Parameters
JavaScript's functions with the Rest parameters (also commonly called Rest Operator) are simply JavaScript's ways to implement variadic functions, and in this BitCode we will take a quick look into it along with some examples.
It allows a function to accept an unlimited number of arguments that will be available as a list inside the function.
The Syntax
The Rest parameters syntax is a sequence of three dots ...
followed by an argument name, all inside the parentheses of a function.
Please do not confuse Rest Parameters with the Spread Syntax, take a look at this BitCode or click the link below to know more about it.
Quick Notes
Some notes to write down before start using the Rest parameter.
- A function can only have one Rest parameter,
- The Rest parameter should be the last parameter in the function definition.
After clearing these points, let's take a look at some examples.
Examples
Let's see a couple of examples using the Rest parameter.
- Find the max of undefined number of items
const findMax = (...numbers) => {
return Math.max(...numbers)
}
console.log(findMax(1, 2, 4, 100, 410, 0))
// Output: 410
- Get the sum of a bunch of number
const sum = (...numbers) => {
return numbers.reduce((x, y) => x + y, 0)
}
console.log(sum(10, 2, 3, 89))
// Output: 104