0

I made a Rock paper scissors game in simple JS and it keeps returning undefined at the end. It returns the userInput and even getComputerChoice() as a random number in a switch, but it keeps saying undefined at the end even though I have no undefined/empty return statements.

JS:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock'){
    return userInput;
  } else if (userInput === 'paper'){
    return userInput;
  } else if (userInput === 'scissors'){
    return userInput;
  } else{
    console.log('Error! not valid input.')
    return;
  
  }
}

const getComputerChoice = () => {
  let randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber){
    case 0:
      return 'rock';
      break;
    case 1:
      return 'paper';
      break;
      case 2:
      return 'scissors';
      break;
    
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice){
    return 'Game was a tie';

  } else if (userChoice === 'rock'){
    if (computerChoice === 'paper'){
      return 'Computer wins!';
    } else{
      return 'User wins!';
    }
  } else if (userChoice === 'paper'){
    if (computerChoice === 'scissors'){
      return 'Computer wins!';
    } else{
      return 'User wins!';
    }
  } else if (userChoice === 'scissors'){
    if (computerChoice === 'rock'){
      return 'Computer wins!';
    } else{
      return 'User wins!';
    }
  } else{
    return 'idk!';
  }
    
  } 

  const playGame = () => {
    const userChoice = getUserChoice('scissors');
    const computerChoice = getComputerChoice();
    console.log('You threw ' + userChoice + ' '+ 'AI threw ' + computerChoice);
    console.log(determineWinner(userChoice, computerChoice));
  }

  console.log(playGame());
jarvic1207
  • 43
  • 3
  • 1
    Does this answer your question? [Chrome/Firefox console.log always appends a line saying 'undefined'](https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined) – Heretic Monkey Apr 28 '23 at 00:06
  • 4
    `playGame` is function that do not have return statement at the end. If function do not have return or it has empty return (just return without anything) that means the function return undefined. – Seti Apr 28 '23 at 00:06
  • 2
    The `getUserChoice` function has an empty `return` in its final `else` block... – Heretic Monkey Apr 28 '23 at 00:07

1 Answers1

3

Your undefined is coming from this line:

console.log(playGame());

The playGame function does not return any value, so that makes it undefined.

Start the game with playGame(), no console.log is necessary.

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116