6

I used to assume that functions always get hoisted to the top of any block of JavaScript code.

For example, this works:

document.addEventListener('something', dummy);
function dummy(){
    console.log('dummy');
}

but this doesn't work and throws ReferenceError in Firefox, but works in Chrome:

if(document){        
    document.addEventListener('something', dummy1);
    function dummy1(){
        console.log('dummy');
    }
}

Fiddle code

Initially, I assumed that Chrome would also throw an error before I tested, but somehow it works correctly. Can someone explain why it doesn't work in Firefox?

mido
  • 24,198
  • 15
  • 92
  • 117
  • You are correct that usually the function location doesn't matter because the file is loaded fully before execution. But in this case its likely because the if statement has some effect where the inner code may not be referenced until executed. Most likely a scope thing. I feel that syntax is ugly anyways. – floor Apr 23 '15 at 03:10
  • 1
    http://stackoverflow.com/questions/14242399/javascript-hoisting-in-chrome-and-firefox | http://stackoverflow.com/questions/25111087/why-is-a-function-declaration-within-a-condition-block-hoisted-to-function-scope | http://stackoverflow.com/questions/4069100/why-cant-i-use-a-javascript-function-before-its-definition-inside-a-try-block Can these help? – Pang Apr 23 '15 at 03:11

1 Answers1

4

It appears this has been an issue for quite a while - here's a reference from 2011: http://statichtml.com/2011/spidermonkey-function-hoisting.html

Apparently Firefox will happily hoist function declarations OUTSIDE of a block, but doesn't do so INSIDE a block. The author of the linked article argues this is (while unexpected) compliant with the ECMA-262 spec, which only allows statements inside of a block...as a function declaration is not a statement. However, I'll note that Firefox happily allows function declarations inside of a block - it merely refuses to hoist them.

S McCrohan
  • 6,663
  • 1
  • 30
  • 39
  • 1
    For what it's worth, the original http://jsfiddle.net/Lfosmckp/1/ exhibits the bad behavior as recently as Firefox 45 but _not_ for Firefox 47. I just happened across this issue today from a customer report, confirmed it on the older version, fixed our code, then discovered "update your browser" would have been a solution as well. Still good do know. – mcdave Aug 05 '16 at 18:03
  • Thanks! Good catch. – S McCrohan Aug 05 '16 at 18:14