Skip to the content

Rest parameters

JavaScript · Unit 10: More on functions

With ... before the last parameter, the function gathers every argument it gets into an array. That way it can take two, three or as many as you want.

This is called a rest parameter: "the rest".

function sum(...numbers) {
  let total = 0;
  for (const n of numbers) {
    total += n;
  }
  return total;
}
console.log(sum(2, 3));
console.log(sum(1, 2, 3, 4));

Prints

5
10

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Fill in the blank so average takes as many grades as you give it.

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    This program should print "Table 4:" and then "taco, water". Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Fill in the blank to add up the prices in the purchases array.

  8. 8. Multiple choice

    In which of these lines do the three dots gather values into an array, instead of taking them out?

  9. 9. Find the case that fails

    total(...prices) should add up all the prices it gets, or give 0 if it gets none. Which call does it fail with?

  10. 10. Predict the output

    Here there are three dots of both kinds. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →