Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

What are rest parameters and how are they used?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Rest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. They are denoted by three dots (...) followed by the name of the array. This feature is useful for functions that need to handle multiple arguments without knowing the exact number in advance.

function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10

Rest parameters

Definition

Rest parameters allow a function to accept an indefinite number of arguments as an array. They are represented by three dots (...) followed by the name of the array.

Syntax

The syntax for rest parameters is straightforward. You place three dots before the last parameter in the function definition:

function myFunction(a, b, ...rest) {
// 'rest' is an array containing the remaining arguments
}

Usage

Rest parameters are useful in various scenarios, such as when you need to handle multiple arguments without knowing their exact number in advance.

Example: Summing numbers

Here's a simple example of a function that sums an indefinite number of arguments:

function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10

In this example, the sum function uses the rest parameter numbers to collect all the arguments passed to it into an array. The reduce method is then used to sum up the elements of the array.

Example: Combining arrays

Rest parameters can also be used to combine multiple arrays into one:

function combineArrays(...arrays) {
return arrays.flat();
}
console.log(combineArrays([1, 2], [3, 4], [5, 6])); // Output: [1, 2, 3, 4, 5, 6]

In this example, the combineArrays function uses the rest parameter arrays to collect all the arrays passed to it into a single array. The flat method is then used to flatten the array of arrays into a single array.

Important points

  • Rest parameters must be the last parameter in the function definition.
  • Only one rest parameter is allowed per function.
  • Rest parameters are different from the arguments object, which is an array-like object available within all non-arrow functions.

Further reading

Edit on GitHub