Javascript - Function variable number parameters


You can create a function to accept a variable number of parameters by using Rest Parameters.

Rest means gathering up parameters and putting them all into a single array.

Spread refers to spreading out the elements of an array or a string.

var showCollections = function (id, ...collection) { 
    console.log(collection instanceof Array); 

showCollections(42, "movies", "music");  // true 

The ... symbol is the rest symbol.

It precedes a named parameter which will become an Array that will store all the remaining parameters passed to the function.

Here, Collections is set to an array.

To make this more clear if we execute the above program this way,

var showCollections = function (id, ...collection) { 

showCollections(42, "movies", "music"); // ["movies", "music"] 

The Rest parameter stores all the remaining parameters after the id parameter into an array called collection.

Excluding the first defined parameter 'id', everything will be placed in the Array.

If we call the function by passing only id, it logs out an empty array [].

If we call showCollections.length, it will give us the number of parameters in the function.

var showCollections = function (id, ...collection) {}; 
console.log(showCollections.length); // 1 

The length property ignores the Rest parameter.

The length property of the function only counts the number of named parameters excluding the rest parameter.

The following code checks the arguments.length inside the function:

var showCollections = function (id, ...collection) { 

showCollections(123, "movies", "music"); // 3 

arguments object records actual number of parameter passed in.

We can use the Rest operator in a function constructor.

var getFirst = new Function("...args", "return args[0]"); 
console.log(getFirst(1, 2));   // 1