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.

const does not mean value it holds is immutable

I see many JavaScript developers have started replacing var with const just because some linter forces them to do so.

const in JavaScript is not only blocked scope but also const variable cannot be reassigned with new content.

It creates readonly reference. It means you cannot reassign value to the const variable. It does not guarantees immutability of the content that it holds.


const person = { name: 'John Doe', age: 33};
person = { name: 'John'} 
// Above line will throw Uncaught TypeError: 
// Assignment to constant variable.

// However, you can change the content of object
// that is referenced by person variable.
person.age = 40;  

So, If you really want to mark your object as immutable then use some other API’s like `Object.freeze`.

There are specific use cases about const variable. Make sure you are intentionally marking some variable as const and not because some linter has that rule.