Rock Paper Scissors ReferenceError userChoice undefined

Hi. Can anyone help me? I constantly see similar posts, but not exactly the same errors:
ReferenceError: userChoice is not defined
if (userChoice === ‘rock’) {
^

Code Below:

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper') {
return userInput;

} else {
console.log('Error!');
}
}

console.log(getUserChoice('paper'));
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 'Sorry, computer won!';
    } else {
      return 'Congratulations, you won!';
  }
  };
  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'Sorry, computer won!';
    } else {
      return 'Congratulations, you win!';  
  }
  };
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'Sorry, computer won!';
    } else {
      return 'Congratulations, you win!';
  }
  };

console.log(determineWinner('rock', 'scissors'));
console.log(determineWinner('paper', 'scissors'));
console.log(determineWinner('rock', 'rock'));

Hey,

You are getting an undefined because userChoice only exists within the context of the function determineWinner. And since you closed off the function immediately after the first if statement, if (userChoice === ‘rock’) will give an error.

const determineWinner = (userChoice, computerChoice) => { // opens function
     if (userChoice === computerChoice) {
         return ‘This game is a tie!’;
     }
}; // closes function
if (userChoice === ‘rock’) { // userChoice does not exist here.
      if (computerChoice === ‘paper’) {
         return ‘Sorry, computer won!’;
      } else {
         return ‘Congratulations, you won!’;
      }
};

Happy coding!

1 Like

Hi.

Thank you so much that makes sense.

I understand I was closing off every function after every if statement.

Thanks again!