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 trialGeorge Nixon
2,551 PointsLet 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?
1 Answer
Steven Parker
231,271 PointsLimiting 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
2,551 PointsThanks 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
231,271 PointsWhen 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.
Michael Caveney
50,144 PointsMichael Caveney
50,144 PointsThe 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?