Search code examples
javascriptarraysalertprompt

how do i fix this javascript prompt=userInput from array to alert problem


Once I run this code i should be getting userInput which is a number between 0-3 and the name of the pizza in alert box. What am I doing wrong?

var menu = [
  "0 = Calzone",
  "1 = Ost & Skinke",
  "2 = Margarita",
  "3 = BBQ Grill"
];

var userPostnummer = prompt("skriv inn postnummer")

if (userPostnummer >= 1000 && userPostnummer <= 1999) {
  alert("gratulerer du får et gratis pizza")
  var userInput = prompt("hvilket meny ønsker du å bestille?" + menu) + alert("pizza " + userInput + " er på vei til postnummer " + userPostnummer)

} else {
  alert("beklager, du er ikke i området hvor vi tilbyr gratis pizza")
};


Solution

  • The reason you receive undefined is because you're trying to use userInput before it's finally declared. You try to use it in an alert in the same operation in the declaration.

    You need to separate the alert to be executed after userInput has got its value, like below.

    If you also want to refer to the "pizza value" in the menu array, you need to replace userInput with menu[userInput]

    var menu = [
      "0 = Calzone",
      "1 = Ost & Skinke",
      "2 = Margarita",
      "3 = BBQ Grill"
    ];
    
    var userPostnummer = prompt("skriv inn postnummer")
    
    if (userPostnummer >= 1000 && userPostnummer <= 1999) {
      alert("gratulerer du får et gratis pizza")
      var userInput = prompt("hvilket meny ønsker du å bestille?" + menu); 
      // Alert is now on its own row.
      // userInput is also replaced with menu[userInput]
      if (userInput < menu.length)
        alert("pizza " + menu[userInput] + " er på vei til postnummer " + userPostnummer)
    
    } else {
      alert("beklager, du er ikke i området hvor vi tilbyr gratis pizza")
    };