How to stop further execution in JavaScript after an if condition is true?


#1


https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/1/5?curriculum_id=506324b3a7dffd00020bf661


I am building a simple game (rock, paper, scissors). I've created an if condition to print an error message when the user inputs an invalid answer but I'm unable to figure out how to stop further execution of my code when the condition is true. And even if the condition is false the error message gets printed

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

if (userChoice != "rock" || "paper" || "scissors") {
    console.log("This isn't a valid answer! Please try again");
    }
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") {
                console.log("Rock wins");
                }
                else {
                console.log("Paper wins");
                }
            }
        else if (choice1=== "paper") {
                if (choice2 === "rock") {
                console.log("Paper wins");
                }
                else {
                console.log("Scissors win");
                }
            }
        else if (choice1 === "scissors") {
                if (choice2 === "paper") {
                console.log("Scissors win");
                }
                else {
                console.log("Rock wins");
                }
            }
        };

compare(userChoice, computerChoice);


#2

ignoring for a second that the if condition might not work perfect, the best solution would be to make a loop, so the user can't progress until they enter a valid choice/option/input.


#3

But is there a solution using the if condition? Thank you.


#4

yep, add an else so the rest of the code only runs when if evaluate to false (valid input)


#5

hey @javaplayer64319 . well, i think u can use break statement (but i dont know if break; works in javascript or not)


#6

to break a loop, sure. But javaplayer didn't want a loop. And if you do include a loop it would be better to keep prompting until the user enters something valid


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.