JavaScript JavaScript and the DOM 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

Ross King
Ross King
18,527 Points

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
6,721 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';
        });
    }
Linas Mackonis
Linas Mackonis
6,721 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