Learn JS - Paper/Scissors/Rock Project Bug

Hello,

I am running through the Learn JS’s Paper/Scissors/Rock project and I can’t seem to figure out why I get “undefined” for certain values when I print the determineWinner function, while with other combinations of user and computer inputs, the conditional logic applies and prints normally. Included is my code with the latest example of an “undefined” result printed to the console. I now know that I should include BOTH cases in each conditional “if” block to match against computer choices, instead of relying on an “else” statement to cover the other (implied) computer choice.

Any help is appreciated. Thank you!


const userChoice = userInput => {
  //lowercase user input
  userInput = userInput.toLowerCase();
  //make sure it's valid input
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput;
  } else {
    console.log("Error. Enter in 'rock,' 'paper,' or 'scissors.");
  }
}

//GET COMPUTER CHOICE
const computerChoice = () => {
  //generate 3 possible choices
  let randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors';
  }
};

//COMPARE CHOICES AND DETERMINE WINNER
const determineWinner = (userChoice, computerChoice) => {
  
  if (userChoice === computerChoice) {
    return 'It\'s a tie!';
  }

  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'Computer won!';
    } else {
      'You won!';
    }
  }

  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'Computer won!';
    } else {
      return 'You won!';
    }
  }

  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'Computer won!';
    } else {
      return 'You won!';
    }
  }
};

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

//Start Program, Display Results
type or paste code here

Hi @dataace07981
you don’t return anything from your first ‘else’ statement, that’s why it isn’t executed.

3 Likes