0

Consider the below code :

<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>
<script type="text/javascript">
    var prizes = ['Watch','A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length-1; btnNum++) {
        // for each of our buttons, when the user clicks it...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // tell her what she's won!
            alert(prizes[btnNum]);
        };
    }
</script>

I wanted it to work as on clicking different buttons, different array values should get appeared. But it alerts only "Fresh Laundry", whichever button is clicked. I'm not getting what's the issue here? Why every function expression assigned through for loop refers to the last element of prizes Array?

1
  • 1
    It's because all closures refer to the same btnNum variable. Commented Feb 22, 2018 at 11:59

1 Answer 1

2

When you will click the value of btnNum will be the last value for all the click event handlers. So your events need to get the correct value.

You can put your event listener inside an Immediately Invoked Function Expression passing the value of btnNum.

var prizes = ['Watch', 'A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length - 1; btnNum++) {
  (function(el) {
    document.getElementById('btn-' + el).onclick = function() {
      alert(prizes[el]);
    };
  })(btnNum);
}
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>

Sign up to request clarification or add additional context in comments.

2 Comments

You know this is one of the most often-duplicated questions in the JavaScript tag. Why answer it rather than pointing to the previous answers?
@T.J.Crowder Makes sense. Noted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.