Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 default values not available in function.arguments?

If I have this ES6 function declaration and invocation:

function myFunction (arg1, arg2 = "bob") {
  console.log("arguments", arguments);
}

myFunction(1);

...the console.log() statement shows only one argument with a value of "1". "bob" is nowhere to be seen. Is this expected and/or desired behavior? I would expect that default values would be available in the arguments object. If not, is there a way to dynamically get all arguments + defaults in some other manner?

Thanks in advance!

like image 996
hairbo Avatar asked Jun 08 '16 14:06

hairbo


People also ask

Can you assign the default values to a function parameters?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

What kind of parameters Cannot have a default value?

An IN OUT parameter cannot have a default value. An IN OUT actual parameter or argument must be a variable.

How do you define a default value for a JavaScript function parameter?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

What are default parameters es6?

Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.


1 Answers

Yes, this is expected and desired. The arguments object is a list of the values that were passed into the function, nothing else.

It is not implicily linked to the parameter variables (that get assigned the default values), like it was in sloppy mode.

Is there a way to dynamically get all arguments + defaults in some other manner?

No. What parameters you have and whether they have default initialisers is static, you don't need to do anything here dynamically. You can do Object.assign([], arguments, [arg1, arg2]) for your example function.

like image 60
Bergi Avatar answered Oct 18 '22 23:10

Bergi