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!