Going beyond Rock, Paper, Scissors in Javascript

Ok… So, here’s the problem I am facing. I just finished doing the rock, paper, scissors module in the Learn Javascript and everything is working fine, but in the code if something is undefined it returns that man has won, I was wondering how I would make it return computer has won if someone inputs something that is not rock, paper, or scissors. I hope this makes sense. (sorry if I did not format this post right. This is my first time :rofl: )

const getUserChoice = userInput => { userInput = userInput.toLowerCase(); if (userInput === 'rock' || userInput === 'paper' || userInput ==='scissors'|| 'bomb') { return userInput } else { console.log ( 'Error, please type valid answer.' ) } } /* console.log (getUserChoice('Rock')) console.log (getUserChoice ('turkey')) */ const getComputerChoice = () => { const randomNumber = ( Math.floor( Math.random() * 3 ) ) switch (randomNumber) { case 0 : return "rock" case 1 : return 'paper' case 2 : return 'scissors' } } const determineWinner = ( userChoice, computerChoice ) => { if ( userChoice === computerChoice) { return 'tie' } if (userChoice === 'rock') { if (computerChoice === 'paper') return 'computer wins' } else { return 'man wins' } if (userChoice === 'paper') { if (computerChoice === 'scissors') return 'computer wins ' } else { return 'man wins'} if (userChoice === 'scissors') { if (computerChoice === 'rock') return 'computer wins' } else { return 'man wins'} if (userChoice === 'bomb') { return 'man wins' } } const playGame = () => { const userChoice = getUserChoice ('water'); const computerChoice = getComputerChoice () ; console.log ( 'You threw: ' + userChoice) console.log ( 'Computer threw ' + computerChoice) console.log ( determineWinner (userChoice, computerChoice)) } playGame ()

in the determineWinner function,
you could put something like:

if ( userChoice === undefined) {
  return  'computer wins'
}

before the other if statements.

also, in the getUserChoice function,
you’ll need to change
userInput ==='scissors' || 'bomb'
to
userInput ==='scissors' || userInput === 'bomb'
in order for that to work the way you expect.
(That’s because 'bomb' always evaluates as true … a non-empty string is truthy so it acts like true when doing stuff like || )
Otherwise what’s in the if-statement condition would always wind up being true so the else block would never run.

1 Like

That makes so much sense! Thank you so much!