JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Raksmey soriya
Raksmey soriya
3,101 Points

Why we can't use var in for loop?

When I use var this code id error but it works when I use let. Anyone can explain to me this?

Here is my code:

const hoverelement = document.getElementsByTagName("li");

for(var i =0; i< hoverelement.length; i+= 1){ hoverelement[i].addEventListener("mouseover" , () =>{ hoverelement[i].textContent = hoverelement[i].textContent.toUpperCase();
});

hoverelement[i].addEventListener("mouseout" , () =>{ hoverelement[i].textContent = hoverelement[i].textContent.toLowerCase();
}); }

1 Answer

Steven Parker
Steven Parker
201,999 Points

It's a scope issue. When you use "var" the loop variable is shared with everything done in the loop. So the value of "i" inside the event handler will be whatever it was after the loop ended (hoverelement.length).

But when you use "let", the value of "i" in the handler will remain what it was when the listener was established.

Before we had "let", handling this situation required a somewhat tricky technique known as a "closure".

Raksmey soriya
Raksmey soriya
3,101 Points

I'm still confusing with it :(

Steven Parker
Steven Parker
201,999 Points

Maybe it would help to point out that the handler is only defined while the loop is running, it doesn't actually run until later when the mouse passes over the element.