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 trialGiorgi Gonadze
3,640 Pointslet and var in for loop
When I use var in for loop instead of let loop does not work. can somebody tell me why? thanks :)
3 Answers
Ross King
20,704 PointsHi Giorgi Gonadze ,
It's a good question and I have become unstuck several times with it.
I'm quoting an answer by Stephen Park here:
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.
See Let vs. Var in a For Loop?
If you want some examples of how this works let me know.
Linas Mackonis
7,071 PointsHi Giorgi, can you post your code, because if I use it this way:
for(var i = 0; i < 10; i++) {
console.log(i);
}
It works!
Giorgi Gonadze
3,640 Points// this does not work
var div = document.getElementsByTagName('div');
for(var i = 0; i < div.length; i++ ){
div[i].addEventListener('mouseover', () => {
div[i].style.backgroundColor = 'red';
});
}
// this works
var div = document.getElementsByTagName('div');
for(let i = 0; i < div.length; i++ ){
div[i].addEventListener('mouseover', () => {
div[i].style.backgroundColor = 'red';
});
}
Billy Chui
6,852 PointsHi there, may i ask why i < 10 ?
Linas Mackonis
7,071 PointsThank you Ross for this explanation.
Giorgi, I guess this explanation is most suitable, because it's simple and concise.
However, if you want to go deeper in to this case, you can read more about it in StackOverflow