Question about function conditions

I’m going back over the Rock / Paper / Scissors assignment, and am trying to write the first function using a ternary operator in order to practice those.

Here’s the function using the ternary operator:

const getUserChoice = userInput => {
 userInput = userInput.toLowerCase();
 let output;
//CHEAT CODE bomb in userInput
   userInput === 'rock' || userInput === 'paper' || userInput === 'scissors' || userInput === 'bomb' ? output = userInput : output = 'Please enter "rock", "paper", or "scissors".'
 return output;
};

console.log(getUserChoice('rock'));  // returns rock
console.log(getUserChoice('roc')); // returns Please enter...

I’m wondering if there’s a way to clean the code up so I don’t have to write “userInput” before each condition. For example, if I redo the code like this:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  let output;
//CHEAT CODE bomb in userInput
    userInput === 'rock' || 'paper' || 'scissors' || 'bomb' ? output = userInput : output = 'Please enter "rock", "paper", or "scissors".'
  return output;
};

console.log(getUserChoice('rock'));  // returns rock
console.log(getUserChoice('roc')); // returns roc

Using parenthesis gets me this:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  let output;
//CHEAT CODE bomb in userInput
    userInput === ('rock' || 'paper' || 'scissors' || 'bomb') ? output = userInput : output = 'Please enter "rock", "paper", or "scissors".'
  return output;
};

console.log(getUserChoice('paper'));  // returns Please enter ...
console.log(getUserChoice('roc')); // returns Please enter...

My question: is there any way to write this so I don’t keep having to type “userInput” before each === condition?

Hello! As far as I know, if you use a ternary operator, you must fully write the conditions out. Of you used a switch…case…default statement, you would avoid writing userInput ===.

1 Like