0

So I've got some code like so:

var word = 'hello'.split('')
var index = 0
for (letter of word) {
    button = document.createElement('button')
    button.innerText = letter
    button.addEventListener('mouseover', function () {
        alert(index)
    })
    index++
    document.body.appendChild(button)
}

The problem I'm having is that the alert will always give me the final value of index rather than 0 - 4 for each element.

I'm sure I've seen a solution to a problem like this before, and I'm honestly fully expecting this to get flagged as a duplicate, but for the life of me I can't seem to figure out the proper search terms to find the answer I'm looking for.

therks
  • 499
  • 3
  • 11
  • tried using index.toString ? – Mixone Jan 13 '18 at 12:17
  • 2
    @Mixone: Would make no difference (other than returning a *string* version of the last value `i` has). – T.J. Crowder Jan 13 '18 at 12:17
  • I think you're looking for the term "closure" - https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Thomas Altmann Jan 13 '18 at 12:18
  • @therks: Since you're using ES2015+ features, one option is `const thisIndex = index;` above the `addEventListener` call and then using `thisIndex` instead of `index` in the handler. See the linked question's answers for the details of why. – T.J. Crowder Jan 13 '18 at 12:18
  • first thing I would have tried if i was debugging honestly, but yeah alert links to the variable in this instance – Mixone Jan 13 '18 at 12:21
  • Thanks very much guys. Sorry again for the dupe. – therks Jan 14 '18 at 14:22

0 Answers0