Running this in Chrome and Firefox gives different answers:
(function() {
if(true) {
function f() { alert("yes"); };
} else {
function f() { alert("no"); };
}
f();
})();
In Chrome the result is 'no' In Firefox the result is 'yes'
Why the difference?
Running this in Chrome and Firefox gives different answers:
(function() {
if(true) {
function f() { alert("yes"); };
} else {
function f() { alert("no"); };
}
f();
})();
In Chrome the result is 'no' In Firefox the result is 'yes'
Why the difference?
Share Improve this question edited Jan 9, 2013 at 17:01 Quentin 944k132 gold badges1.3k silver badges1.4k bronze badges asked Jan 9, 2013 at 16:59 BillRBillR 1114 bronze badges3 Answers
Reset to default 13Declaring functions inside conditional statements is non-standard, so do not do that. That's a known issue. You may use function expressions instead of the declarations:
var f;
if(true) {
f = function() { alert("yes"); };
} else {
f = function() { alert("no"); };
}
f();
The famous Kangax article on function expressions gives some additional details:
FunctionDeclarations are only allowed to appear in Program or FunctionBody. Syntactically, they can not appear in Block
({ ... })
— such as that ofif
,while
orfor
statements. This is because Blocks can only contain Statements, not SourceElements, which FunctionDeclaration is.
The same article also says:
It's worth mentioning that as per specification, implementations are allowed to introduce syntax extensions (see section 16), yet still be fully conforming. This is exactly what happens in so many clients these days. Some of them interpret function declarations in blocks as any other function declarations — simply hoisting them to the top of the enclosing scope; Others — introduce different semantics and follow slightly more plex rules.
From V8 (Chrome JavaScript engine) bug tracker:
Not a bug. Firefox is the only browser that does what you're expecting.
The behavior of Safari and IE on this is the same as Chrome's/V8's.
This happens due to Firefox lack of function hoisting, as conceived in ECMAScript 5.
Chrome correctly assigns a value to f() before running the body of the function, so the first version of f() is overwritten by the second one.
SpiderMonkey (Firefox’s JavaScript engine) runs the code without pre-assignin a value to f(),
so it uses the only value that encounters on its way: function f() { alert("yes"); };
what's function hoisting?
JavaScript’s function scope means that all variables declared within a function are visible
throughout the body of the function. Curiously, this means that variables are even
visible before they are declared. This feature of JavaScript is informally known as hoisting:
JavaScript code behaves as if all variable declarations in a function (but not any
associated assignments) are “hoisted” to the top of the function.
sources:
http://statichtml./2011/spidermonkey-function-hoisting.html
2011 - o'reilly - javascript - the definitive guide 6th edition