Rest Parameter in ES6 - Supporting an arbitrary number of arguments

js.Srijan

Table of Contents

The ...rest parameter

To support an arbitrary number of arguments in our function like Math.min() and Math.max() instead of ignoring them as our greetings function did in the previous example, we can use the rest parameter(...rest) to collect some or all the arguments in an array.

function greetings(...names){ for(let name of names){ console.log(`Hello ${name}!`); } } greetings("John Doe", "Harry Potter", "Dr. Strange"); // Output: // Hello John Doe! // Hello Harry Potter! // Hello Dr. Strange!

In the above example, "names" is the name of the array in which all the parameters are collected.

As the rest returns a pure array, you can do all the array related operations on the names array. For example,

names.length; // 3 names.join(', '); // John Doe, Harry Potter, Dr. Strange

Supporting fixed and variable arguments

Using the rest parameter, we can also create a function that supports fixed and variable arguments.

function greetings(greeting, ...names){ for(let name of names){ console.log(`${greeting}, ${name}!`); } } greetings("How are you!", "John Doe", "Harry Potter", "Dr. Strange"); // Output: // How are you!, John Doe! // How are you!, Harry Potter! // How are you!, Dr. Strange!

Rest parameter must be last

As the rest parameter collects all the remaining arguments, it must be the last argument in the list.

Correct:

function func(arg1, arg2, ...rest){};

Wrong:

function func(arg1, ...rest, arg2){};

We will love to see examples and scenarios where you have used the rest parameters. Feel free to add them in the comments below :).

Share this

Share on social media