4

Am I going crazy - js can forward reference within scope right?

If I am right, is this a serious scope bug in Firefox 22.0?

if (true) { 

    test();

    function test() { 
        alert("success"); 
    } 
}

The above code fails with test() being undefined. If the code is executed outside of the if statement (or if just the function definition is moved outside the if statement??!?) then everything is ok. The same error occurs (not defined) inside other scopes like do .. while etc.

The above code works fine as is in IE and Chrome etc!

* update *

Not sure it's daft or unreasonable to expect to be able to do this (certainly makes sense semantically in sudo code) - but the js gods decided only statements can appear in such blocks (as mentioned in the link referencing spidermonkey / ECMA stuff from basilikum) - so no it is - especially with inconsistent browser handling (if not in strict mode). Thanks all.

LFN
  • 89
  • 1
  • 5
  • 1
    have a look at this: http://statichtml.com/2011/spidermonkey-function-hoisting.html – basilikum Aug 06 '13 at 11:43
  • 2
    The *only* closure scopes in JavaScript are functions. `while` and `if` use curly braces, but they do not create scope blocks. Declaring a function in an `if` branch does not make any sense, semantically. Don't do it. – Tomalak Aug 06 '13 at 11:45
  • I have modified the question slightly to make more sense. Yes, I should have used the term scope and not closure. More importantly I have unlearned something bad. Makes perfect sense now. Shame it's not consistent accross browsers! – LFN Aug 06 '13 at 12:00
  • 1
    @LFN - it is consistent if you use strict mode. – Spudley Aug 06 '13 at 12:06
  • @LFN The terms "scope" and "closure" are interchangeable in JS. A function creates a new scope and at the same time it creates a closure. `if` or `while` do neither. – Tomalak Aug 06 '13 at 12:20

1 Answers1

5

Firefox has non native extensions to ECMAScript.

In ECMAScript, it's invalid to have a function declaration inside a block statement (though most browsers allow it in non-strict mode), but in Firefox, they have a syntax called a function statement, which does allow this. The difference is that the function statement isn't evaluated on a separate pass like a function declaration, so it is similar to a function expression in that you can't use it before it's defined.