This is what your code actually looks like when it is compiled:
function f() { return "global"; }
function test(x) {
var result = [];
var f;
if (x) {
f = function () { return "local"; } // block-local
result.push(f());
}
result.push(f());
return result;
}
The f
variable (the variable holding the function pointer) is declared at the top of the function, but it is defined within the conditional.
JavaScript also has a feature called: strict mode. This was put in after the original development of the language to enforce some best practices and some rules to keep developers from making incorrect assumptions about how they think the language works based on other languages with a similar syntax. In this instance, strict mode actually changes the scoping of the new f
function.
The following code:
function f() { return "global"; }
function test(x) {
"use strict" // STRICT MODE TAG INSERTED HERE
var result = [];
if (x) {
function f() { return "local"; } // block-local
result.push(f());
}
result.push(f());
return result;
}
test(true);
test(false);
produces the following results result:
["local","global"] //test(true);
["global"] //test(false);
It overrides the default scoping rules and makes sure that the new declaration of f
only applies to within the conditional where it was defined.