Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox: function hoisting error

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?

like image 664
mido Avatar asked Apr 23 '15 03:04

mido


People also ask

How can we stop a function from getting hoisted?

Some ways to avoid hoisting are: Use let or const — As explained above, using let or const instead of var would throw an exception and not let the program run, hence helping catch the issue earlier. Use function expressions instead of function declarations.

Why is a function not hoisted?

Function expressions aren't added to the scope at all, hoisted or otherwise. This is because they are being used as a value, as opposed to function declarations, whose purpose is to create functions you can call by name.

Is hoisting a bug?

As we all know, the variable declaration is one of the basic and essential aspects of any programming language such as C language, C++, etc. However, JavaScript has a small odd, known as Hoisting, which can turn a flawless-looking declaration into a subtle bug.

Can hoisting work in function?

In JavaScript, hoisting is only done for variable and function declarations but not assignments. So, when a variable is assigned then hoisting doesn't work and gives a TypeError or a ReferenceError.


1 Answers

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.

like image 73
S McCrohan Avatar answered Oct 16 '22 01:10

S McCrohan