1

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
        }
   }
});
user3021621
  • 341
  • 1
  • 4
  • 14

1 Answers1

1

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.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • if the code wasn't inside the if block, and was decalred right away in the function. was the inner function hoisted in ES6? my question is the if statement has an impact on the hoisting of the function? – user3021621 Jul 04 '16 at 20:39
  • Yes, function-level function declarations are hoisted on the function-level scope. – Bergi Jul 04 '16 at 20:41
  • but in more advanced ES, the function is hoisted also in if blocks? – user3021621 Jul 04 '16 at 20:43
  • Yes, see the explanation in the first linked question. – Bergi Jul 04 '16 at 20:58