ES6 Rest Parameter

The rest parameter is introduced in ECMAScript 2015 or ES6, which improves the ability to handle parameters. The rest parameter allows us to represent an indefinite number of arguments as an array. By using the rest parameter, a function can be called with any number of arguments.

Before ES6, the arguments object of the function was used. The arguments object is not an instance of the Array type. Therefore, we can't use the filter() method directly.

The rest parameter is prefixed with three dots (...). Although the syntax of the rest parameter is similar to the spread operator, it is entirely opposite from the spread operator. The rest parameter has to be the last argument because it is used to collect all of the remaining elements into an array.

Syntax
snippet
function fun(a, b, ...theArgs) {
  // statements
}
Example
snippet
function show(...args) {
  let sum = 0;
  for (let i of args) {
      sum += i;
  }
  console.log("Sum = "+sum);
}

show(10, 20, 30);
Output
Sum = 60

All the arguments that we have passed in the function will map to the parameter list. As stated above, the rest parameter (...) should always be at last in the list of arguments. If we place it anywhere else, it will cause an error.

The rest parameter with the following syntax will cause an error.

function show(a,...rest, b) {
  // error
 };

Difference between Rest Parameter and arguments object

The rest parameter and arguments object are different from each other. Let's see the difference between the rest parameter and the arguments object:

  • The arguments object is an array-like (but not array), while the rest parameters are array instances. The arguments object does not include methods such as sort, map, forEach, or pop, but these methods can be directly used in rest parameters.

Rest Parameters and Destructuring

Destructuring means to break down a complex structure into simpler parts. We can define an array as the rest parameter. The passed-in arguments will be broken down into the array. Rest parameter supports array destructuring only.

By using the rest parameter, we can put all the remaining elements of an array in a new array.

Let's see an illustration of the same.

Example
snippet
var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];  
  
// destructuring assignment  
var [a,b,...args] = colors;  
console.log(a);   
console.log(b);   
console.log(args);
Output
Violet Indigo [ 'Blue', 'Green', 'Yellow', 'Orange', 'Red' ]

Rest Parameter in a dynamic function

JavaScript allows us to create dynamic functions by using the function constructor. We can use the rest parameter within a dynamic function.

Example
snippet
let num = new Function('...args','return args');
console.log(num(10, 20, 30));
Output
[ 10, 20, 30 ]
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +