0

There is 3 different button, once the user clicks on the button it will come out random price, but it displays undefine

const prizes = ['toy1', 'toy2', 'toy3'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
// User click on each button
document.getElementById(`btn-${btnNum}`).addEventListener("click", function() {
// Winner
 alert("Congratulations you have won a " + prizes[btnNum] + "!");
});
}
  • replace your var with a let keyword inside the loop. Your loop declares its' iteration variable with a `var` keyword which is affecting the global scope. So in this case, once your loop is done the `btnNum` will have the value of 3 which is obviously out of the range. – Eduard Jan 15 '22 at 07:01

0 Answers0