Rest Parameter In Javascript ES6.

Introduction.

Rest Parameters in ES6 Javascript is a function syntax that accepts all arguments passed to the function as an array. It is a more readable syntax that replaced the previous ES5 Argument's objects and is primarily used to check arguments passed to the function.

Syntax.

        function (a, b, c, ...theArgs){
          //some texts
        }

Rest Parameters are prefixed with three dots, '...' called the spread operator. This spread operator is attached to the last parameter in the function syntax. It indicates that there is an additional number of parameters before the last parameter. In the syntax above, ...theArgs is the Rest Parameter. In a defined function, there can be only one Rest Parameter and that must be the last parameter.

Examples.

In the example below, the function maps the first and second arguments to a and b respectively, while the third argument, ...manyMoreArgs, is an array that contains the third, fourth, fifth and as many arguments that the user includes.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five");

// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five"]

Even if there are no extra arguments to fill into the rest parameter, it would simply be an empty array [], the rest parameter would never be undefined.

// using the same function definition from above

myFun("one", "two");

// a, "one"
// b, "two"
// manyMoreArgs []

Rest Parameter is quite extensive and has more complicit uses.

References.

This post briefly talks about Rest Parameters, which itself is a wide topic in ES6 Javascript. To read more on the subject, the following topics are quite useful.