Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) 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
210,871 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
210,871 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.