Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confusion when using the != operator with the || operator in JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)) {
   …
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading