Rock, Paper, Scissors - Mystery?

Hello all,

I’m working through the JavaScript exercises, the “Rock, Paper, Scissors” project to be specific. I want to know why a certain line of code behaves a certain way?

For example, if the user input is ‘bomb’, I want this piece of code to accept it and print it to the console. But what really happens is:

Case I:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if(userInput === ('rock'||'paper'||'scissors'||'bomb'))
    return userInput;
  else
    console.log('Error!');
}

Output:

Error!
User choice is: undefined
Computer choice is: rock
undefined

Case II:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if(userInput === ('bomb'||'rock'||'paper'||'scissors'))
    return userInput;
  else
    console.log('Error!');
}

Output:

User choice is: bomb
Computer choice is: rock
User has won ;)

What does precedence of ‘bomb’ placement has to do with the logic? Thanks in advance.

1 Like

How does the operator || behave? Go read up on that, then compare to how you use it.
Also note that you can find that this is the issue by looking at what you did to obtain that “undefined” and repeatedly narrowing down which operations went wrong until you have just that left

1 Like

Ok, so looks like this is the right way to do it?

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if(userInput === 'rock'|| userInput === 'paper'||userInput === 'scissors'||userInput === 'bomb')
    return userInput;
  else
    console.log('Error!');
}

Thanks for the tip!

Could you please help me understand what you meant by

Also note that you can find that this is the issue by looking at what you did to obtain that “undefined” and repeatedly narrowing down which operations went wrong until you have just that left

It was strange because the previous logic worked for ‘rock’, ‘paper’ and ‘scissors’ as input and did not work only for ‘bomb’ :thinking:

1 Like

work only for ‘bomb’

That’s a bit like saying a stopped clock is accurate twice a day.

You’re comparing to the result of this expression:

('bomb'||'rock'||'paper'||'scissors')

But since you know the left value of === when it results in true, then you already know what the right side is as well even without looking at it.

1 Like