Rest parameter under the hood…

You know the rest parameter (usually prefixed with ...) allows functions or methods to accept indefinite numbers of parameters.

This parameter is actually gathering the values from arguments and creates an array of values from it.

How? Let’s see with code using ES6 rest parameter and it’s corresponding transpiled version.

Simple snippet with rest parameter

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

Obviously, line 2 will print an array:

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

You wonder, How it’s an array? Let’s inspect it via transpiled version.

Below code is transpiled using BABEL.

Transpiled version:

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

Under the hood, the rest parameters are actually derived from arguments object of called function, `print`. Please notice carefully variable days on line# 5.

It’s value is set to an array whose length is equal to number of arguments passed.

Later, elements from arguments are copied to variable days (element by element from line# 8 to 10).

Another Example

Second snippet

In the second code snippet, please note there is a parameter multiplier apart from rest parameter ...numbers. Hence, copying will not begin from first element instead it started from second element till last one.

See transpiled version for more details.

Transpiled version

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

Dattatraya Kale

Aspiring agile software craftsman, clean code, polyglot, in love with different programming paradigm. I am on a never-ending journey towards mastery of software.

Leave a Reply