Reputation: 55
I'm new to JavaScript and programming. I'm writing a program to play rock paper scissors, and I want to catch when a user fails to enter a correct choice.
Here's my userChoice() function, with an if statement to catch incorrect choices.
function userChoice() {
let choice = prompt('Choose rock, paper, or scissors.', 'rock')
// Convert user input to lowercase
choice = choice.toLowerCase()
// If the user doesn't choose 'rock', 'paper', or 'scissors'...
if (choice != 'rock' ||
choice != 'paper' ||
choice != 'scissors') {
alert('Please choose a valid choice.') // ... ask them to make a valid choice.
return userChoice(); // call the userChoice() function again.
} else {
console.log(`Player1 chooses ${choice}`)
return userChoice()
}
}
When I call the function as written, it always triggers the if statement.
It only does this if I use the || operator to define multiple != comparisons. If I just use one != comparison, without the || operator, it works fine.
if (choice != 'rock') // Works fine!
So it seems that I'm not quite understanding how to use || and != together.
Edit: I thought that || tested for the first falsy value, and && tested for the first truthy value. I had it backwards, and should have used && to find the first falsy value. Thanks for pointing out my error.
Upvotes: 0
Views: 94
Reputation: 27245
The way you have your condition written it’s always true, because it can’t be all three of those things at once.
In english it translates to “if it’s not rock OR it’s not scissors OR it’s not paper…”
If it’s rock it’s not scissors, if it’s scissors it’s not paper, etc, so your test is always true.
You want AND: “If it’s not rock AND it’s not scissors AND it’s not paper…”
It’s easy to get tripped up by because we tend to think “if it’s not rock or paper or scissors” but the logic here is testing each comparison independently and ORing them.
Alternatively you could do:
const options = ["rock", "paper", "scissors"];
if (!options.includes(userChoice)) {
…
}
Upvotes: 1