Conditional Statements: Using || (or)

I am currently working on the rock paper scissors project, and I have a quick question.

Why is the following not correct syntax?
if (userInput === “rock” || “scissors” || “paper”)

This is the code I ended up having to use, but I feel its a little long.
if(userInput === “rock” || userInput === “scissors” || userInput === “paper”)

Any advice is much appreciated!

Hello, @leemingzheng21772155, and welcome to the forums!

It may seem a bit long, but that’s how to test multiple expressions in JavaScript. Continue your learning, and after learning about arrays, come back to this, and see if you kind find a more efficient solution. :wink:

As to why your original code doesn’t work. Let’s examine what happens in a statement like you wrote:

let a = "hot"
//since a is equal to 'hot' we should expect true to be logged
console.log(a === "hot" || "cold" || "pizza")

//reassign a
a = "potato"
//since a is not equal to 'hot' the next truthy value will be logged, so 'cold'
console.log(a === "hot" || "cold" || "pizza")

//change it up again
console.log(a === "hot" || false || "pizza") //expect 'pizza'



In your case, using an if statement, the condition will always evaluate to true. If userInput does equal ‘rock’, it’s true. If userInput doesn’t equal ‘rock’ the condition inside the parenthesis will evaluate to the first truthy value because you are using ||. Any non-empty string in JavaScript has a bool value of true, so you end up with:

if ("scissors")

if then coerces the bool value of "scissors" which is true, so no matter what value is assigned to userInput, the condition for your if statement will evaluate to true.

  console.log("True again!")
}else {
  console.log("That's false!")


True again!


That makes sense! Thank you very much! :slight_smile:

1 Like