Search code examples
javascriptarraysif-statementprompt

Array, prompt, if, if else statement


I'm trying to create a web page as below and the code is not working. Could anyone shed some light on it?

  • Create a website that accomplishes the following:
  • Create an array of your favorite bands.
  • With a prompt, ask the user's favorite band.
  • If it's one of your favorites, alert: "YEAH I LOVE THEM!"
  • If it's not, alert: "Nah. They're pretty lame."
  • HINT: You will need to research how to use .indexOf().
  • HINT: You will need to research how to use .toLowerCase().\

    <!DOCTYPE html>
    <html lang="en-us">
      <head>
        <meta charset="UTF-8">
        <title>Array Activity - Unsolved</title>
      </head>
      <body>
    
        <script>
    
    
    
         var myBands = ["Chromatics","ACDC","Michael Jackson"];
    
         var UserGuess = prompt("Who is your favourite?");
    
         var userGuessLower = userGuess.toLowerCase(); 
    
    
    
    
          if (myBands.indexOf(userGuessLower) === -1) {
               alert("Na They're pretty lame.");
             }
    
          else {
               alert("OMG I love them too!");
             }
    
          </script>
    
          </body>
    
          </head>
          </html>
    

Solution

  • You have a syntax error where you are using userGuess instead of UserGuess. Moreover, the purpose of using toLowerCase() is to remove the case sensitivity between the two strings when comparing, whereas what you are doing is changing the input to lower case while keeping the array elements to have some uppercase letters. Here is the solution:

    var myBands = ["chromatics","acdc","michael jackson"];
    var UserGuess = prompt("Who is your favourite?");
    var userGuessLower = UserGuess.toLowerCase(); 
    if (myBands.indexOf(userGuessLower) === -1) {
         alert("Na They're pretty lame.");
    }else {
         alert("OMG I love them too!");
    }