Code Challenge: What’s Wrong With This Game?

Since the start of 2015, I’ve been working on some JavaScript courses on Treehouse and elsewhere. In an effort to improve, I’m going to do a JavaScript code challenge every Monday for at least 10 weeks. Here’s the first one. I would love feedback in the comments!

Here is a link to the original problem on Interview Cake. In short, you have the following code. The syntax is correct, but the behavior is off.

<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>

<script type="text/javascript">
    var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length; 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>

It didn’t take me long to figure out the actual issue, but the solution was a different story. It eluded me for several minutes. Here’s my solution minimized.

Continue reading