- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.12 Rest Parameters and the Spread Operator
As you have seen, you can call a JavaScript function with any number of arguments. To process them all, declare the last parameter of the function as a “rest” parameter by prefixing it with the ... token:
const average = (first = 0, ...following) => { let sum = first for (const value of following) { sum += value } return sum / (1 + following.length) }
When the function is called, the following parameter is an array that holds all arguments that have not been used to initialize the preceding parameters. For example, consider the call:
average(1, 7, 2, 9)
Then first is 1 and following is the array [7, 2, 9].
Many functions and methods accept variable arguments. For example, the Math.max method yields the largest of its arguments, no matter how many:
let result = Math.max(3, 1, 4, 1, 5, 9, 2, 6) // Sets result to 9
What if the values are already in an array?
let numbers = [1, 7, 2, 9] result = Math.max(numbers) // Yields NaN
That doesn’t work. The Math.max method receives an array with one element—the array [1, 7, 2, 9].
Instead, use the “spread” operator—the ... token placed before an array argument:
result = Math.max(...numbers) // Yields 9
The spread operator spreads out the elements as if they had been provided separately in the call.
Note that you can use the spread operator even if the function that you call doesn’t have any rest parameters. For example, consider the average function of the preceding section that has two parameters. If you call
result = average(...numbers)
then all elements of numbers are passed as arguments to the function. The function uses the first two arguments and ignores the others.
The syntax for default arguments and rest parameters are equally applicable to the function syntax:
function average(first = 0, ...following) { . . . }