Rock, paper or scissors project

Continuing the discussion from Rock, paper or scissors project:

const getUserChoice = userInput => { userInput = userInput.toLowerCase(); if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper') { return userInput; } else { console.log('Error, please type: rock, paper or scissors'); } }; 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 'This game is a tie.'; } if (userChoice === 'rock') { if (computerChoice === 'paper') return 'The computer won!'; } else { return 'You won!'; } if (userChoice === 'paper') { if (computerChoice === 'scissors') { return 'The computer won!'; } else { return 'You won!'; } } if (userChoice === 'scissors') { if (computerChoice === 'rock') { return 'The computer won!'; } else { return 'You won !'; } } }; console.log(determineWinner('rock', 'scissors')); console.log(determineWinner('paper', 'scissors')); console.log(determineWinner('rock', 'rock'));

Why do I get the result undefine?

Hi,
In this block;

if (userChoice === ‘rock’) {
if (computerChoice === ‘paper’)
return ‘The computer won!’;
} else {
return ‘You won!’;
}

you’re missing the brackets for the second, inner ‘if’ statement, so the else is being connected to the outer one.
So, userChoice === ‘rock’, but computerChoice doesn’t equal ‘paper’, so the code runs through the rest of the function, gets to the end and doesn’t return a value.

(little note: if the code block for something like an if statement is just one line, it doesn’t need brackets { }, which is why you’re not getting an error for the line:
return ‘The computer won!’;
)

Thanks a lot! I really appreciate the help.

1 Like