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.

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.

Source: JavaSript – Stack Overflow

November 23, 2021
Category : News
Tags: conditional-statements | javascript | logical-operators

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.