The simple version of this question is: Why is there an undefined error in the 3rd example from the snippet below?
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"
There's no problem with giving parameter names and instance variable names the same name.
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.
The caller's arguments passed to the function's parameters do not have to have the same names.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With