Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRaksmey soriya
3,101 PointsWhy 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
231,269 PointsIt'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
3,101 PointsRaksmey soriya
3,101 PointsI'm still confusing with it :(
Steven Parker
231,269 PointsSteven Parker
231,269 PointsMaybe 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.