1 thing to know when using js default function parameters, 'arguments' keyword behaviour

albertodeago88 profile image Alberto De Agostini ・2 min read

Some days ago at work I encountered an unexpected (unexpected for me at least) behaviour when using the default function parameters. I'm going to explain what and I hope this will help some folks out there.

Default function parameters

You can skip to the next chapter if you already know well default function parameters added with es6 javascript.

For those who are not 100% familiar with this functionality, it was introduced with es6 features and it allow you to give a default value to function parameters like a normal human being would do. Let's see some examples:

Pre es6:

var fun = function(param1, param2) {
  param1 = typeof param1 !== "undefined" ? param1 : 1;
  param2 = typeof param2 !== "undefined" ? param2 : 2;
  // the two previous line was one of the many ways we were setting a default value

  // ... do function stuff ...

With es6:

var fun = function(param1 = 1, param2 = 2) {
  // ... do function stuff ...

MUCH MUCH better right?

Yep, I agree. I would strongly suggest you to start using this if you are not already.
You can read more in the official MDN documentation, also keep in mind that if you want to support old browsers (ie11 for example) you will need to transpile your code, using something like Babel. I won't dive deeper into this because we could write a book about it and there are many many great articles out there about this.

Interaction between arguments and default parameters

This is where the behaviour I wasn't expecting hit me like a fist in the face.
Let's take this code:

const fun = function(p1 = 1, p2 = 2, p3 = 3) {

What do you think the snippet will log in console?
a) 0
b) 1
c) 2
d) 3
e) undefined

If you guessed d you answered like I did the first time, thus you were wrong.
The correct answer is b.
This is because arguments always contains the actual provided parameters, ignoring the defaults.
Infact we can see that arguments ignore also the function definition:

const fun = function(p1, p2, p3) {
  console.log(arguments.length); // this will log 5
fun(1, 2, 3, 4, 5);

So be careful when using arguments keyword combined with default parameters.

I hope this was helpful, feel free to contact me on twitter


Editor guide