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 JavaScript and the DOM (Retiring) Responding to User Interaction Listening for Events with addEventListener()

George Nixon
George Nixon
2,551 Points

Let vs. Var in a For Loop?

I was having trouble getting this code to work as a loop through items:

for (var i = 0; i < listItems.length; i+=1) {

listItems[i].addEventListener('mouseover', () => { listItems[i].textContent = listItems[i].textContent.toUpperCase(); })

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

Then I changed 'var' in the for loop to 'let' and it worked...can anyone clarify why that small change made the difference?

Michael Caveney
Michael Caveney
50,144 Points

The difference between the two is that declaring "i" with let would prevent it from being hoisted and locks it to the scope of the for loop, but that doesn't seem to be the case here?

1 Answer

Steven Parker
Steven Parker
231,008 Points

Limiting the scope of "i" actually is the case here. With "var", "i" becomes a global that all the handlers share, so when the event occurs, the value of "i" is what it had when the loop ended, which is not a valid index for any element.

But with "let", each handler has a separate value for "i" which is still what it was when the handler was established, and therefore correct for the element receiving the event.

George Nixon
George Nixon
2,551 Points

Thanks Steven,

Does that mean that var stuck with a value of 0 throughout? That would explain why the first item in the list adopted the desired behavior, but the others didn't.

Steven Parker
Steven Parker
231,008 Points

When the loop ends, "var i" would have a value of listItems.length, which is one more than the highest valid list item index. So I would not expect any item to operate. Without seeing the whole code I don't know why it seemed to work.