Rock-Paper-Scissors Project: Game works great until userInput is undefined

Hey all!

My game runs great as long as the userInput is defined here:

if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors' || userInput === 'turtle')

If the userInput isn’t defined, the console.log prints:
image

In the instance that the userInput is not defined, I would like the consol.log to print only the ‘Error Message: Please…’ line. I’ve tried this through several different if statements without success:

const playGame = () => {
  const userChoice = getUserChoice('turtle');
  const computerChoice = getComputerChoice();
//if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors' || userInput === 'turtle'){
//if(getUserChoice !== console.log('Error Message: Please select from Rock, Paper, or Scissors.'){
//if(getUserChoice === 'rock' || getUserChoice === 'paper' || getUserChoice === 'scissors' || getUserChoice === 'turtle'){
//if(getUserChoice === userInput){
//if(userInput){
  console.log(`You threw: ${userChoice}`);
  console.log(`The computer threw: ${computerChoice}`);
  console.log(determineWinner(userChoice,computerChoice));
}

Note: Some of the above if lines effectively stop the consol.log from printing more than the error message when a userInput is not defined, but those solutions create a new problem; consol.log won’t print anything when the userInput is defined.

I’ve been googling and trying different solutions for a couple of hours and I’m just not understanding what I’m missing. Some guidance or a push in the right direction would be much appreciated!

Thank you!

Heya! I think I understand what you want, which is for it to just print out your error message, and not try to play the game with an ‘undefined’ choice?

In which case, this is a great use of javascripts ‘truthy’ conditions. This basically means not empty strings evaluated to true, and undefined variables evaluate to false - and can therefore be used in if statements. Just changing this line in your code might do what you want:

if (userChoice) {
    console.log(`You threw: ${userChoice}`);
    console.log(`The computer threw: ${computerChoice}`);
    console.log(determineWinner(userChoice,computerChoice));
  }

What this says is ‘if the userChoice is truthy (i.e. not empty) then do the other stuff’. And therefore you shouldn’t get undefined printing out if you don’t select something.

Is that the behaviour you were after?

1 Like

@Benji9876

It makes so much sense and works!! I can’t believe I didn’t try this. Thank you so much!! :slight_smile:

1 Like

No problem at all, really glad it’s working :partying_face:

1 Like