Search code examples
javascriptecmascript-6scopehoistingjavascript-function-declaration

Closure and function hoisting- not working on firefox


The following code gave an error, on some version in firefox browser - linksHandle is not defined.

The code is comprised of a function that at the bottom has a function named linksHandle. As far as I know this function is supposed to be hoisted when the the function that it is defined in, is invoked.

Therefore the function defined for the event 'mMenuReady' should be able to access it, because it enclosures all the function and variables that were defined in it's execution context.

Why do some firefox versions need the function declaration (linksHandle) to be defined before in order for the 'mmenu' callback to enclose the function?

document.addEventListener('readystatechange', function() {
    if (document.readyState === 'interactive') {

        if (typeof jQuery === 'function') {
            // callback function that is invoked later by the event that is triggered ->  $(window).trigger("mMenuReady")
            $(window).on('mMenuReady', function() {
                var links2 = Array.prototype.slice.call(document.querySelectorAll('#mm-mainMenu a'));
                links2.forEach(linksHandle);
            });
        }

        function linksHandle(elem) {
            // function code
        }
   }
});

Solution

  • Function declarations inside blocks are only allowed since ES6. They do hoist inside your if body (not to the whole function), but not in older versions of FF that did implement them as "function statements" that were not hoisted (and actually completely invalid in strict mode) having caused issues like yours.