Take a look at the code snippet below:
<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++) {
// when each button is clicked...
document.getElementById('btn-' + btnNum).onclick = function() {
// display what the user has won!
alert(prizes[btnNum]);
};
}
</script>
In this scenario, using 'var' to declare the variable btnNum in the 'for' loop causes issues. Clicking on any button will result in the same value being alerted, which is the last element of the 'prizes' array.
When 'let' is used instead of 'var', everything functions correctly. Each button now displays a different array element upon clicking. So, why does replacing 'var' with 'let' fix the problem?
<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 (let btnNum = 0; btnNum < prizes.length-1; btnNum++) {
// for each button click event...
document.getElementById('btn-' + btnNum).onclick = function() {
// show the corresponding prize!
alert(prizes[btnNum]);
};
}
</script>