Javascript Hoisting in Chrome And Firefox
Asked Answered
M

3

11

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?

Monogenetic answered 9/1, 2013 at 16:59 Comment(0)
D
13

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.

Downhill answered 9/1, 2013 at 17:6 Comment(0)
E
5

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.

Edaedacious answered 9/1, 2013 at 17:8 Comment(0)
F
2

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.com/2011/spidermonkey-function-hoisting.html
2011 - o'reilly - javascript - the definitive guide 6th edition

Favored answered 1/9, 2014 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.