0
0
JavascriptConceptBeginner · 3 min read

What is Rest Parameter in JavaScript: Simple Explanation and Example

The rest parameter in JavaScript allows a function to accept an indefinite number of arguments as an array. It is written as ...name in the function definition and collects all remaining arguments into a single array.
⚙️

How It Works

Imagine you are packing a suitcase and you don't know exactly how many clothes you will bring. Instead of making separate compartments for each item, you just put all clothes into one big bag. The rest parameter works similarly in JavaScript functions.

When you define a function, you can use ...rest to gather all extra arguments passed into the function into one array. This means you don't have to specify a fixed number of parameters. The function can handle any number of inputs easily.

This makes your functions flexible and able to work with varying amounts of data without extra code.

💻

Example

This example shows a function that sums any number of numbers using the rest parameter.

javascript
function sumAll(...numbers) {
  let total = 0;
  for (const num of numbers) {
    total += num;
  }
  return total;
}

console.log(sumAll(1, 2, 3));
console.log(sumAll(5, 10, 15, 20));
Output
6 50
🎯

When to Use

Use the rest parameter when you want a function to accept any number of arguments without knowing how many in advance. This is useful for functions like calculators, logging tools, or event handlers where inputs can vary.

For example, if you want to create a function that joins words into a sentence, the rest parameter lets you pass any number of words easily.

Key Points

  • The rest parameter collects extra arguments into an array.
  • It must be the last parameter in the function definition.
  • It helps create flexible functions that handle many inputs.
  • It is different from the arguments object because it is a real array.

Key Takeaways

The rest parameter gathers all extra function arguments into an array.
Use ...name syntax as the last parameter in a function.
It makes functions flexible to handle any number of inputs.
Rest parameters are real arrays, unlike the older arguments object.