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"