I'm learning some ES6
features and of course came across the let
keyword and its new scope (differs from var
)
and I came across an example about the tricky scope of var
and its hoisting.
but I can't fully understand why I get this result:
var events = ['click', 'dblclick', 'keydown', 'keyup'];
for (var i = 0; i < events.length; i++) {
var event = events[i];
document.getElementById('btn').addEventListener(event, function() {
document.getElementById('result').innerHTML = 'event: ' + event;
});
}
<button id="btn">Click Me!</button>
<span id="result"></span>
I understand that var event
is hoisted outside the for
loop but why is it getting the last event ('keyup') in the array every iteration of the loop?
Is the addEventListener
function asynchronous and by the time its attaching the event the value of the event changes?