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 trial

JavaScript

why is program only works with let but not with var ?

https://teamtreehouse.com/library/listening-for-events-with-addeventlistener

for(let i=0;i< selectli.length; i++){

selectli[i].addEventListener('mouseover',()=>{

selectli[i].textContent=selectli[i].textContent.toUpperCase();

});

selectli[i].addEventListener('mouseout',()=>{

selectli[i].textContent=selectli[i].textContent.toLowerCase();

});

}

this loop and functions only work when let is used in for loop but when i change the let to var the functions and event listers did'nt work i want to know why

3 Answers

Steven Parker
Steven Parker
243,656 Points

:point_right: The problem is with the value at the time the handler is called.

Using either var or let will set up the handlers, but later, when an event occurs, what the handler does will be different.

The handler uses the variable "i" to index the element that should be changed. But if var was used, the value of "i" no longer refers to any of the existing elements, since it was incremented beyond them during the set-up loop. On the other hand, if let was used, the value of "i" is still what it was when the handler was established, so the handler will still work.

:information_source: So it's important to limit the scope of any variables that will be used inside the handler routine.

Thanks for providing the snapshot, though I realize now that I should've spotted the problem from your excerpt.

Steven Parker
Steven Parker
243,656 Points

:point_right: It may require more than a tiny code excerpt to identify the issue.

Particularly since you are using variable names that differ from the ones used in the video. But you could make a snapshot of your workspace and post the link to it here.

In the meantime, one possible cause might be that the variable already exists in global scope, and using var interferes with it but using let does not. But if that's not it, I'd have to see the snapshot.

thanq very much now i understands the difference