Question about Javascript if statement parameters

I was just doing the ‘rock, paper, scissors’ exercise on the full stack course, and had a thought while inputing some parameters into an if statement. The answer to this particular exercise is to use the || or logical operator and to ask for one of three options. Could the same result be returned with either of the two codebytes below:

const getUserChoice = userInput => { userInput - userInput.toLowerCase(); if(userInput === 'rock', 'paper', 'scissors'){ return userInput; } else{ console.log('Please select a valid option'); } };

or

const getUserChoice = userInput => { userInput - userInput.toLowerCase(); if(userInput === 'rock' || 'paper' || 'scissors'){ return userInput; [codebyte] [/codebyte] } else{ console.log('Please select a valid option'); } };

rather than writing:

const getUserChoice = userInput => { userInput - userInput.toLowerCase(); if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){ return userInput; } else{ console.log('Please select a valid option'); } };

Just thought there may be a short hand way to write this same code. Any help would be much appreciated.

The second one doesn’t work because when you write:

if (condition == "something" || "somethingelse")

You’re actually checking if a) condition == "something" and (importantly) b) whether “somethingelse” is true. Since any non-empty string is a truthy value, the second part of the condition will always return true, and so the entire condition will always evaluate as true, and whatever’s in the if block will run.


A similar thing (in terms of outcome) happens with the first codebyte as well.

EDIT (I had to research the comma): As it turns out, the comma (,) is an actual operator in JavaScript; an operator which evaluates the whole expression, and returns the last one. So, in your case, the if statement essentially becomes:

if ("scissors")

Because "scissors" is the last ‘expression’ in the list, and, since that is a truthy value, the if statement will always evaluate to true.

I hope this helps!

Thank you for taking the time to offer so much great and informative feedback. I appreciate your help and advice.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.