DEV Community

Cover image for Rest Parameter in ES6 - Supporting an arbitrary number of arguments
Srijan
Srijan

Posted on • Originally published at hackinbits.com

Rest Parameter in ES6 - Supporting an arbitrary number of arguments

In javascript, you can call a function with an arbitrary number of arguments. A function can be defined with any number of arguments. If extra arguments are present, it does not matter and will be simply ignored.

function greetings(name){
console.log(`Hello ${name}!`);
}

greetings("John Doe", "Harry Potter", "Dr. Strange");
// Hello John Doe!
Enter fullscreen mode Exit fullscreen mode

The above function will not give any error. But it will only use the first parameter "John Doe" and ignore the remaining ones.

Many built-in functions also support an arbitrary number of arguments. For example, Math.max() and Math.min() accepts an arbitrary number of arguments and returns the maximum and minimum of the values passed to it.

Math.max(1, 2, 4, 9, 100, 6);
// 100

Math.min(1, 2, 4, 9, 6);
// 1
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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){};
Enter fullscreen mode Exit fullscreen mode

Wrong:

function func(arg1, ...rest, arg2){};
Enter fullscreen mode Exit fullscreen mode

This article was first published on hackinbits.com

Top comments (0)