Going back to a prior choice?


#1



https://www.codecademy.com/courses/javascript-beginner-en-ZA2rb/0/4?curriculum_id=506324b3a7dffd00020bf661


Given the scenario where a player doesn't pick any of the valid answers in an IF/SWITCH statement. Is there a way to forcefully make the player repeatedly go back to a question until he/she picks a valid one?

In my code, I try to say prompt(variable storing anther prompt) in an ELSE and in a DEFAULT. But it returns me an error.

I know I could make a Function but that would overly complicate things. There has to be a simpler way to do that.

I appreciate any help.


var user = prompt("Do you wish to proceed? YES or NO?").toUpperCase();

switch (user)
{
    case 'YES':
        var fightOrRun = prompt("If you wish to proceed, you first need to defeat the gatekeeper. Will you FIGHT or RUN?").toUpperCase();
        if (fightOrRun === "FIGHT")
        {
            console.log("You fight the gatekeeper and win");
        }
        else if (fightOrRun === "RUN")
        {
            console.log("The gatekeeper kills you");
        }
        else
        {
            console.log("Choose either FIGHT or RUN");
            prompt(fightOrRun);
        }
        break;
    case 'NO':
        console.log("You run away like a chicken. Game over.");
        break;
    default:
        console.log("Choose either YES or NO");
        prompt(user);
        break;
}


#2

Why not use a do while loop? It is already covered in a lesson you should passed

It is perfect, think about it. It will prompt the user at least once for input, and then as long as needs be till the user gives something valid


#3

But how do I code that? I'm trying to do this:

while (user !== "YES" || "NO")
{
prompt(user)
}

However, even when I write a valid answer, the code just repeats itself in an infinite loop.


#4

first of, you need to compare at both sides of the or operator:

while (user !== "YES" ||  user !== "NO")

this will still cause a infinity loop. If the user enters something invalid, both conditions are true, true or true is true, the loop continues to run. If the user enters something valid, true or false is still true. Either use the and (&& ) operator instead, or use equal (==):

while (user !== "YES" &&  user !== "NO")

or:

while (user == "YES" ||  user == "NO")

Both will work.