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?
Declaring 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 complex rules.
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