mardi 5 mai 2020

How to nest an if-statement inside a function? - Javascript

Now that I have a recursive function, I wonder what is best in order for the same flow to continue. Nest an another function, isn't it? In other words, I would like another prompt that asks the user's age when the user answers yes to the first prompt. They way I've nested it makes the prompts pop up in a way that I can't figure out:

  function showPrompt(msg) {
  var str = prompt(msg).toLowerCase();
  if (str === "yes") {

            function showPrompt(firstQuestion) {
                    var age = prompt(firstQuestion).toLowerCase();
                    if (age < "21") {
                        alert("You're too young. Go home.");
                    } else if (age >= "21") {
                        alert("Welcome.");
                    } else {
                        showPrompt(firstQuestion);
                    }       
            }

        showPrompt("How old are you?");

  } else if (str === "no") {
    alert("goodbye.");
  } else {
    showPrompt(msg);
  }
}

showPrompt("Do you like gambling?");

Aucun commentaire:

Enregistrer un commentaire