Course contentsShow
← JavaScript
Lesson 412 of 2,72311. FunctionsFree lesson

Rest Parameters: Collecting Remaining Arguments

Use rest parameter syntax (...args) to gather all extra arguments into a true array.

Rest Parameters: Collecting Remaining Arguments

You'll learn how to gather all extra arguments into a real array using rest parameter syntax.

The Core Idea

When you don't know exactly how many arguments a function will receive, you can use a rest parameter to collect all remaining arguments into a true array. The syntax is three dots followed by a parameter name: ...args.

Unlike the arguments object (which is array-like but not a real array), rest parameters give you an actual array with all array methods available.

How Rest Parameters Work

function sum(...numbers) {
  console.log(numbers); // Real array!
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

console.log(sum(1, 2, 3));        // 6
console.log(sum(5, 10, 15, 20)); // 50
console.log(sum());               // 0 (empty array)

The rest parameter ...numbers collects all arguments into an array called numbers.

Combining Regular Parameters with Rest

You can have normal parameters before the rest parameter:

function greet(greeting, ...names) {
  console.log(greeting);      // "Hello"
  console.log(names);         // ["Alice", "Bob", "Charlie"]
}

greet("Hello", "Alice", "Bob", "Charlie");

The first argument goes to greeting, and all remaining arguments are collected into the names array.

Important: The rest parameter must always be the last parameter.

Think of It Like This

Imagine a restaurant where the first person orders a specific dish, and everyone else orders "whatever's left on the menu." The rest parameter is like saying "...and everyone else."

Key Takeaway: Rest parameters (...paramName) collect all remaining arguments into a true array, giving you full array functionality and cleaner code than the arguments object.