How to make closures in a loop remember the variable value from their iteration in JavaScript?
Hi everyone! I'm a beginner in JavaScript and ran into a problem I don't understand at all. I'm writing simple code: I want to add click handlers to several buttons so that each one outputs its own number.
Here's my code:
```javascript
const buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
console.log('Button number ' + i);
});
}
```
But when I click any button, the console always outputs "Button number 5" (the last value of i), no matter which button I clicked. I read that this is related to closures, but I don't understand how to fix it. Why does this happen? How can I make each button remember its own number? Please explain in simple terms with examples. Thanks in advance.
No answers yet.
Log in to leave an answer