Recently I noticed a behavior difference between Firefox and other browsers for the following javascript code:
var condition = true;
A();
function A() {
var x=0;
for(var i=0; i<10; i++) {
if(condition) {
++x;
B();
}
function B() {
console.log("B function. x = "+x);
}
}
}
Chrome, Opera, IE output:
B function. x = 1
B function. x = 2
B function. x = 3
B function. x = 4
B function. x = 5
B function. x = 6
B function. x = 7
B function. x = 8
B function. x = 9
B function. x = 10
Firefox output:
ReferenceError: B is not defined
However, there are no complaints from Firefox and gives out the same result as other browsers, if I put the definition of function B
before the call, like this:
for(var i=0; i<10; i++) {
function B() {
console.log("B function. x = "+x);
}
if(condition) {
++x;
B();
}
}
Based on this quote from Mozilla developer site:
Functions must be in scope when they are called, but the function declaration can be below the call
I understand the call, A()
works. But I am not clear on why there is a difference in behavior between Firefox and others in calling B()
, when the call is before definition.
While trying to narrow down the cause, I read about function hoisting here, which says Firefox doesnt do hoisting when inside an if
block, but the definition was never inside the if
statement in my case, so Im confused.