Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Hoisting in Chrome And Firefox

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?

like image 457
BillR Avatar asked Jan 09 '13 16:01

BillR


1 Answers

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 of if, while or for 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.

like image 127
bfavaretto Avatar answered Sep 21 '22 01:09

bfavaretto