Search code examples
javascriptswitch-statementdefault

Javascript - Make switch: default restart prompt


I am trying to ask the user a simple question:

// Write your code below!
var food = prompt("Do you like waffles?");

switch (food) {
    case "yes":
    case "Yes":
        alert("Good!");
        break;
    case "no":
    case "No":
        alert("But why!");
        break;
    default:
        var food = prompt("That's not an answer, Do you like waffles?");
        break;
}

The default works but only once. I want to re-prompt the user if he/she enters an answer that is not yes or no infinitely. What is going on here?


Solution

  • function askForFood( questionArgument ){
      var food = prompt( questionArgument );
      switch (food.toLowerCase()) { // be DRY! Use lowercase!
        case "yes":                 // And lowercase it is!
          alert("Good!");
          break;
        case "no":
          alert("But why!");
          break;
        default:
          askForFood("That's not an answer, Do you like waffles?"); // to hell with it
          break;
      }
    }
    
    askForFood("Do you like waffles?"); // First time ask nicely

    Why the above works?
    Cause the use of a function that's able to do repeat the work more times.
    Simply pass your "Question" as an argument to the function.
    case default: with that same function call, but usign a different question this time.

    P.S: thanks to the use of toLowerCase() the user can also write "yeS" and your program will play ball with friends without caring much...


    If it's not for school, you could also play with your code and do it (I like it!) like this:

    var questionary = {
      "yes" : "Good!",
      "no"  : "But why!",
    };
    
    function askForFood( question ){
      var answer = prompt( question ).toLowerCase();
      if(answer in questionary) alert( questionary[answer] ); // Self explanatory
      else askForFood( "That's not an answer" ); // ♫ do it again!
    }
    askForFood("Do you like waffles?");