Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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) { . . . }
  • + Share This
  • 🔖 Save To Your Account