Skip to content

Instantly share code, notes, and snippets.

@jgrant29
Last active December 6, 2016 21:48
Show Gist options
  • Save jgrant29/561c65988c381f97158ce2e855ddf594 to your computer and use it in GitHub Desktop.
Save jgrant29/561c65988c381f97158ce2e855ddf594 to your computer and use it in GitHub Desktop.
JavaScript
Hey mentor,
I was working through an assignment last night and came across a bug. I'm so confused!
The text in the alert is showing up as "undefined" instead of either "A Unicorn", "A hug", or "Fresh Laundry" and I'm not quite sure what's going on. Can you point me in the right direction?
-Student
@jgrant29
Copy link
Author

jgrant29 commented Dec 6, 2016

Hey Student,
Put the event handler inside a closure, otherwise btnNum will always be the last one by the time the button is clicked.

```

Button 1!
Button 2!
Button 3!

  <script type="text/javascript">
    var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
      (function(position) {
        document.getElementById('btn-' + btnNum).onclick = function() {
          // tell her what she's won!
          alert(position);
        };
      })(prizes[btnNum]);
    }
  </script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment