Rest parameters

The rest parameters allow function or methods to accept indefinite numbers of parameters. The rest parameters are the instance of an Array. It internally uses the arguments.

Only the last parameter of function qualifies as a “rest parameter”.

The last parameter (say, theArgs) of a function can be prefixed with … which place all ...theArgs to a “standard” javascript array.

Under the hood, the rest parameters are actually derived from arguments object. It’s very interesting to know what could be the transpiled code.

Let’s see via example using rest parameter and it’s transpiled version.

First snippet: The function with Rest parameter ‘…days’

Obviously, line 2 will print an array:

[ 'Monday', 'Tuesday', 'Wednesday' ].

How it’s an array? Let’s inspect transpiled code for above code snippet.

Transpiled version of first code snippet. The days variable is initialised as array and copies element from argument object.

See the variable days, it’s an array. It gets values from argument object.


Another Example

Second snippet

In the second code snippet, please note there is a parameter multiplier apart from rest parameters. The second code snippet has different transpiled code.

Transpiled version of second snippet. Please note argument objects first element is skipped.

Please note, the rest parameter ‘numbers’ is copied from argument object however copy is started from second element in argument object.