Use of let vs var in for-loop with Event Listener

Use of let vs var in for-loop with Event Listener
0

#1

Greetings. Appreciate some help to clear up some confusion on how event listener works, especially in for- loop. I have 2 buttons in a html page with the following js script.

<script>
const bttnArray = document.querySelectorAll('button');
console.log(bttnArray.length);  // 2

for (var i = 0; i < bttnArray.length; i++) { // -------------------(1)
    bttnArray[i].addEventListener('click', () => {
        console.log(i);  // ---------------------------------------------(2)
    })
}
</script>

When I use ‘var i = 0’ in line (1), I get an output of ‘2’ in line (2) each time I click on the buttons, doesn’t matter which button. However, if I change ‘var’ to ‘let’ in line (1), I get a ‘0’ and ‘1’ when I clicked on the buttons.

(a) How does the ‘i’ in console.log in line (2) know what is the value to use, since there are different values of i throughout the iterations (i has a value of 0, 1 and 2 throughout the iterations)?

(b) I read that ‘let’ is block scoped while ‘var’ is global scope. How does that affect how the addEventListener is run in terms of the ‘i’ value used in line (2)?

Thank you in advance!


#2

When i is in the global scope as is the case when declaring it with var, then by the time you click on one of the buttons, the for loop has long been finished and the console.log(i) uses the last known value of i, which would be 2.

The blocked scoped i using the let keyword “locks in” the value of i at the time when it was referenced inside the for loop.


#3

Thank you. Clear and concise explanation!