JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Loop in listItems

Why the 'var' keyword doesn't work when we replace it in listItems loop? Meanwhile, there's no problems with the 'let'

1 Answer

Steven Parker
Steven Parker
172,127 Points

With "let", the scope is limited to the loop block, so you get a fresh variable each time through the loop. But with "var", the scope is the entire function (or global if not in a function), so there's only one variable that is shared.

Either way is fine while the loop runs, but it makes a difference to any event listener that was set up in the loop. When the event happens later, the value in the "let" variables will still be what it was in the loop, but the value in the "var" will have changed.

Thank u very much, Steven