Next Steps: What if a user makes an inappropriate choice like 'dog'? How can we extend the function to handle that?


#1

What if a user makes an inappropriate choice like 'dog'? How can we extend the function to handle that?

var userChoice = prompt("Do you choose rock, paper or scissors?");

var computerChoice = Math.random();
if (computerChoice < 0.34) {
	computerChoice = "rock";
} else if(computerChoice <= 0.67) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2){
    if (choice1 === choice2){
        return "The result is a tie!"
    }
    
    else if (choice1 === "rock"){
        if (choice2 === "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
    
    else if (choice1 === "paper"){
        if (choice2 === "rock"){
            return "paper wins"
        }
        else{
            return "scissors wins"
        }
    }
    
    else if (choice1 === "scissors"){
        if (choice2 === "rock"){
            return "rock wins";
        }
        else{
            return "scissors wins";
        }
    }
}

compare(userChoice,computerChoice);

#2

Well you could either go on learn about loops and wrap your userChoice in a while or even better do while loop. Or the easier way add an else statement in the compare function that simply returns "Invalid choice!" as you made an if or else if case already for all valid options :slightly_smiling: