0

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"); 
 } 
4
  • it should just be playerChoice != "paper" Commented May 6, 2015 at 9:21
  • why are you not usin if condition?? Commented May 6, 2015 at 9:21
  • tried it with != still not working!!! Commented May 6, 2015 at 9:25
  • @Minhajraz != vs !== shouldn't make a difference here. Have you tried switching to using && instead of || as per the various answers? Commented May 6, 2015 at 9:40

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explanations @james Thorpe.
2

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

The issue is with the !=, is it not?
I thought && will only return 'true' if all the values are true. I want it to return true if either case is true
@PaulFitzgerald See the Strict Inequality operator vs the Inequality operator. !== is perfectly valid.
@PaulFitzgerald: No, it isn't.
Any one with any other idea?? I am stack here!
|
0

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.....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.