Firefox: function upgrade error

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

For example, this works:

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

but this does not work and throws a ReferenceError in Firefox, but works in Chrome:

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

Script code

At first, I assumed that Chrome would also throw an error before I test, but somehow it works correctly. Can someone explain why it does not work in Firefox?

+6
source share
1 answer

It seems like this has been a problem for quite some time - here's a link from 2011: http://statichtml.com/2011/spidermonkey-function-hoisting.html

Apparently, Firefox will happily take up the function of declaring an OUTSIDE block, but it will not do that INSIDE block. The author of a related article claims that this (while unexpectedly) complies with the ECMA-262 specification, which only allows statements within a block ... as a function declaration is not an expression. However, I want to note that Firefox happily resolves function declarations within a block - it simply refuses to raise them.

+4
source

Source: https://habr.com/ru/post/985741/


All Articles