0

I have a function with this form:

function main () {
    if(!false){
        if(document.addEventListener){
            document.addEventListener("touchstart", do_something);
            document.addEventListener("click", do_something);
        }
        function do_something(){
            //doing something here
        }
    }
}

My problem is that in firefox (but not in chrome or safari), the listener throws an error: ReferenceError: do_something is not defined

I thought that functions defined in that form were always read before execution, and functions defined as var do_something(){} are read at execution time.

Is this correct? Why is this happening only on Firefox?

EDIT: More info: if I mote it before the if, the function works and no error shown

Vandervals
  • 5,774
  • 6
  • 48
  • 94
  • 2
    Where is do_something called? – epascarello Aug 10 '15 at 14:59
  • 3
    What's the purpose of `if(!false)`? – Amit Aug 10 '15 at 14:59
  • I made an update. Also the purpose is to show you that there is an if sentence that will be true, in case it is important to know.... Of course on real code there is a condition that makes sense. – Vandervals Aug 10 '15 at 15:00
  • @CrayonViolent - why? it's not passed as a string... – Amit Aug 10 '15 at 15:01
  • The answer is in the duplicate, but here's another [source](http://whereswalden.com/2011/01/24/new-es5-strict-mode-requirement-function-statements-not-at-top-level-of-a-program-or-function-are-prohibited/) – Amit Aug 10 '15 at 15:08
  • 1
    Until (and including) ES5, function *declarations* weren't actually allowed inside blocks. Although browsers allow it, they implement different semantics. Chrome hosts the function in the enclosing (function or global) scope, Firefox treats it more like a function expression. The behavior was standardized in ES6 but may not be implemented in browsers yet (also I'm not sure about the exact behavior). – Felix Kling Aug 10 '15 at 15:22

0 Answers0