1

I found a weird behavior that I couldn't understand even reading MDN doc about hoisting. It says that functions and variables gets moved to the top of the scope except variable initialization. So how does below code work?

const element = document.getElementById('#el');

element.addEventListener('click', function() {
   console.log(myVariable); // 'myValue'
});

const myVariable = 'myValue'; // Variable initialization.

As you can see, the myVariable initalization happens after the anonymous function for click event listener.

passionateLearner
  • 722
  • 1
  • 7
  • 19
  • 1
    The declaration of `myVariable` is hoisted. The value is then initialized in your bottom line. Thus, it is available to the function in your event handler and its value is the one set during initialization. Declaration and initialization are different. – Jamie Dixon May 13 '22 at 21:55
  • 1
    Adding an event listener and the event listener being triggered are two different things. `myVariable = 'myValue'` is executed before the click event will trigger. This is basically the opposite of [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron), but the reason is the same. – Ivar May 13 '22 at 21:56

0 Answers0