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

Shane Harper
8,864 PointsWhy does "let i = 0" work in the for loop instead of "var i = 0"?
When I tried to make the for loop for the mouseover/mouseout event listeners, it did not work when i said "var i = 0." After changing it to "let i = 0", it worked. Why is this the case?
for (let i = 0; i < listItems.length; i++) { listItems[i].addEventListener('mouseover', () => { listItems[i].textContent = listItems[i].textContent.toUpperCase(); }); listItems[i].addEventListener('mouseout', () => { listItems[i].textContent = listItems[i].textContent.toLowerCase(); }); }
1 Answer

Steven Parker
243,095 PointsIt's a matter of scope. Variables created with "let" have block scope, so each event listener has a separate value for "i", which is what it needs to work correctly. On the other hand, "var" has function scope, which means that all the event handlers share the same value of "i", which ends up as the value that stopped the loop; and that value is not valid for any of the listeners.
Shane Harper
8,864 PointsShane Harper
8,864 PointsThat makes a lot more sense now - so is it generally better practice to use the "let" keyword in for loops instead of "var"?
Steven Parker
243,095 PointsSteven Parker
243,095 PointsThe difference won't always be as significant as it is here. But it is considered good practice to use "const" where possible, and "let" otherwise.
I have to admit that I still use "var" occasionally also, but mostly as a way to make global declarations obvious. But always be mindful of the scope in any case.