The following javascript fragment goes into an infinite loop. Why is that?
var playerChoice=prompt("Choose paper or rock or scissors");
while (playerChoice !=="paper" || playerChoice !=="rock" || playerChoice !== "scissors"){
playerChoice=prompt("Choose paper or rock or scissors");
}
3 Answers 3
Because when a new choice is made, it will always match at least two of the conditions, and since you've used the OR (||) operator, will continue with the loop. You need to use the AND (&&) operator instead:
var playerChoice=prompt("Choose paper or rock or scissors");
while (playerChoice !=="paper" && playerChoice !=="rock" && playerChoice !== "scissors"){
playerChoice=prompt("Choose paper or rock or scissors");
}
Now when a valid choice is made, two of the 3 inner conditions are still met, but because the last one isn't, the whole condition will evaluate to false and the loop will not execute.
1 Comment
You need to use &&. You need to quit the loop if the choice is either one of the valid choices
while (playerChoice != "paper" && playerChoice != "rock" && playerChoice != "scissors") {
playerChoice = prompt("Choose paper or rock or scissors");
}
Demo: Fiddle
In your case assume, playerChoice is paper but when evaluating your condition playerChoice !=="rock" is true and since you have used || if any of the condition is true the loop will get executed
6 Comments
!=, is it not?!== is perfectly valid.You're using OR where you should be using AND, whether Rock, Paper or Scissors is entered two of your conditions will evaluate as TRUE so you'll go around the loop again, and again, and again.....
playerChoice != "paper"!=vs!==shouldn't make a difference here. Have you tried switching to using&&instead of||as per the various answers?