Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a default parameter and function parameter have the same name?

The simple version of this question is: Why is there an undefined error in the 3rd example from the snippet below?

Intuition why it should work

The default value should, it seems, be taken from the "outer" a variable, ie, the one whose value is 1. The first test shows that "shadowing" works with lexical scope: a inside the function refers only to a inside the function, and is unaware of the outer a.

Given that, I see no reason why the 2nd and 3rd tests are different. It is simply an arbitrary coincidence that in the 3rd test, I happen to be setting the default value to a variable in the enclosing scope that has the same name as the function's parameter.

var a = 1;
var b = 100;



function defaultParamTest1(a) {
  console.log(a + 1);
}

function defaultParamTest2(a = b) {
  console.log(a + 1);
}

function defaultParamTest3(a = a) {
  console.log(a + 1);
}


defaultParamTest1(); // WORKS! => NaN, since function a "shadows" outer a.
defaultParamTest2(); // WORKS! => 101, as expected
defaultParamTest3(); // ERROR! => "Uncaught ReferenceError: a is not defined"
like image 671
Jonah Avatar asked Jun 05 '16 22:06

Jonah


People also ask

Can parameters have the same name?

There's no problem with giving parameter names and instance variable names the same name.

How different is default parameter from the function parameter?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Do parameters and arguments have to have the same name?

The caller's arguments passed to the function's parameters do not have to have the same names.

Can parameter have same name as variable?

Answer. When a parameter has the same name as a variable defined outside, instead of the function using the variable defined outside, it will only reference the value that was passed to the parameter. So, parameters will be used over variables of the same name within a function.


1 Answers

OK, I haven't read the spec itself because the last Krell brain boost I had is wearing off, but I think the issue is that the right-hand side expressions for default parameters include the set of parameters in their scope. Thus, the a you reference on the right-hand side of the = is the a on the left-hand side, not the a in the enclosing context. (The context is available of course, as you note, but parameter names shadow that context.)

The evaluation of the right-hand side default expressions is an invocation time thing in ES2015.

like image 61
Pointy Avatar answered Sep 25 '22 01:09

Pointy