'How does function within addEventListener gets hoisted?
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|