Search code examples
javascripthoisting

JS: Why does function declaration order matter when inside a conditional block?


a();
function a() {
    $('.doit').text('Text was replaced (a)');   
}

if ($('.doit2').length) {
    b();
    function b() {
         $('.doit2').text('Text was replaced (b)');   
    }
}

a() is called correctly, while b gives an error "b is not defined". Why?

(I've read about hoisting but function b is declared, not a variable. Or am I wrong?)

See fiddle - Firefox is raising an error, while Chrome works.


Solution

  • By Javascript specs, function declarations are not allowed in conditionals (or any other blocks). Therefore, this is technically undefined behavior. Some browsers attempt to create a reasonable behavior. However, you shouldn't rely on browsers being able to interpret this correctly.

    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.

    http://kangax.github.io/nfe/#function-declarations-in-blocks