CodeBlanks Logo Icon CodeBlanks

The rest parameter

JavaScript course · Beginner · Lesson 83/133

Learn to collect unlimited arguments as an array with ...args.

The rest parameter

Sometimes you cannot know in advance how many arguments a function will receive. The rest parameter solves this: put ... before the parameter name and all remaining arguments are collected into an array.

Example: function sum(...nums) { return nums; }. Here nums is an array. In the call sum(1, 2, 3), nums becomes [1, 2, 3]. In sum(), nums is the empty array [].

Rest is a real array

The rest parameter is always a real array. That means you can use all array methods like forEach, map and reduce directly on it.

Example: function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }. Because nums is an array, reduce works on it. This is a big advantage over the legacy arguments object, which you will see in the next lesson.

Exercise Sum the numbers

Define a function called sum. It should take a ...nums rest parameter. Inside, initialize a sum variable with let total = 0. Loop over the array with for (let n of nums) and add each element with total += n. Then return the total with return total.

Show example solution
function sum(...nums) {
  let total = 0;
  for (let n of nums) {
    total += n;
  }
  return total;
}

Test yourself

  1. What is nums in the call sum(4, 5, 6)?

    function sum(...nums) {
      return nums;
    }
    sum(4, 5, 6);
    • A single number: 4
    • A string: "4,5,6"
    • An array of all arguments: [4, 5, 6]
    • undefined
    Show answer

    An array of all arguments: [4, 5, 6] — Correct. The rest parameter gathers all arguments into an array.

  2. Add the rest parameter

    function sum(
      ____
    ) {
      let total = 0;
      for (let n of nums) {
        total += n;
      }
      return total;
    }
    Show answer
    function sum(
      ...nums
    ) {
      let total = 0;
      for (let n of nums) {
        total += n;
      }
      return total;
    }
  3. Rest parameter features

    ...nums
    Rest parameter
    nums
    Array name
    for (let n of nums)
    Loop over the array
    return total
    Returns the sum

All lessons in Beginner