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()

Giorgi Gonadze
Giorgi Gonadze
3,640 Points

let 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

Hi 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
Linas Mackonis
7,071 Points

Hi 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
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
Billy Chui
6,852 Points

Hi there, may i ask why i < 10 ?

Linas Mackonis
Linas Mackonis
7,071 Points

Thank 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