Rest Operator

What is Rest Parameter?

The ES6 version provides a new parameter type called Rest Parameter which is prefixed with three dots ( ...).

Rest Parameter (also known as the representation of the remaining parameters) allows you to represent an infinite number of arguments as an array.

The syntax for using Rest Parameter:

function  myFunc (a, b, ... args ) {
   // code
}

The last parameter (args) that begins with an ellipsis ( ...) is called Rest Parameter ( ... args).

All the arguments you pass into the function will map to the parameter list.

In the above syntax, the first argument maps to a, the second argument maps to b, and the third, fourth, ... arguments will be stored in Rest Parameters args as an array.

For example:

myFunc (1, 2, 3, 'x', 'y', 'z');

At this point, the parameter argswill contain the following values:

[3, 'x', 'y', 'z']

If you pass only the first two parameters, the remaining parameters will be an empty array:

myFunc(1, 2); 

... then arg sit would be:

[] 

However, the Rest Parameter must be at the end of the argument list, otherwise, it will cause an error:

// Rest Parameter must be placed at the end
function myFunc (a, ...args, b) {
    // code
}

Some examples using Rest Parameters in JavaScript

To understand Rest Parameter better, let's do some examples.

For example, suppose we want to add many numbers (but it is unclear how many numbers there are). We use Rest Parameters as follows:

function Sum(... args ) {
    let total  =  0 ;
    for (const x of args ){
        total +=  x ;
    }
    return total ;
}

Sum(1, 2, 3);

Running the program we get the results:

6

n this example, argsit's an array, so we can use a loopfor of to iterate over its elements and sum them up.

Suppose the function Sum()can pass arguments with many different data types such as numbers, strings and booleans... But what if you just want to sum the numbers?

Simply, before adding, we check its type:

function Sum(... args ){
    let total  =  0 ;
    for (let x of args){
        if (typeof x === 'number'){
            total += x ;
        }
    }
    return  total ;
}

Then if you have arguments that mix up the data, it can still be calculated:

let res = Sum (1, 'a', null, undefined, 2);
console.log(res);

Result:

3

Or use the sublime way by combining the filter() function and reduce() function like this:

function crystalSum(...args) { 
    return args.filter(e => typeof e === 'number')
        .reduce((prev, curr ) => prev + curr);}

However, the arguments object itself is not an instance of the Array type, so you cannot use the method directlyfilter(). In ES5 you must useArray.prototype.filter.call()the following:

function crystalSum(){
    return Array.prototype.filter.call(arguments, e => typeof e === 'number')
      .reduce((prev, curr) => prev + curr );
}

As you can see, using Rest Parameters as in the first example makes the code much more compact. Let's say you need to filter arguments based on a specific type like number, string, boolean, and null.

function filterData(type, ...args) {
    return args.filter(e => typeof e === type);
}

let res = filterData('string', 1, 'a', null, undefined, 2);
console.log(res);

Result:

["a"]

Rest Parameters and Arrow Functions

Arrow Function has no argument object, so if you want to pass some arguments to an arrow function, you must use Rest Parameter.

For example:

const “Sum  = (... args) =>  {  
  return args.filter(e => typeof e === 'number').reduce((prev, curr) => prev + curr );
  };
const res = crystalSum(1, 'a', null, undefined, 2);
console.log(res);

Result:

3

Rest Parameters and Dynamic Functions

JavaScript allows you to create dynamic functions via constructor . And Rest Parameter can be used in a dynamic function.

Here is an example:

var printArgs = new Function('...args', 'console.log(args)' );
printArgs(1 , 2, 3);

Result:

[1, 2, 3]

Last updated