Problem with Rock, Paper, Scissors - Javascript

Hi!
I don´t understand why the output of the line 22 and line 58 can be different.
Thanks!

LINE 22 console.log(COMPUTER IN GETCOMPUTERCHOICE ${getComputerChoice()});
LINE 58 console.log(Computer threw: ${computerChoice});

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  if (userInput === "rock" || userInput === "paper" || userInput === "scissors" || userInput === 'bomb') {
    return userInput;
  } else {
    console.log("The user input can be only 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";
  }
};

console.log(`COMPUTER IN GETCOMPUTERCHOICE ${getComputerChoice()}`);

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return "The 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!";
    }
  }
  if (userChoice === "bomb") {
    return "You won!";
  }
};

const playGame = () => {
  const userChoice = getUserChoice("bomb");
  const computerChoice = getComputerChoice();
  console.log(`You threw: ${userChoice}`);
  console.log(`Computer threw: ${computerChoice}`);
  console.log(determineWinner(userChoice, computerChoice));
};
playGame();

[/codebyte]

getComputerChoice() randomly generates "rock" or "paper" or "scissors" each time.
So calling this multiple times would randomly generate a new result each time, which may or may not be the same as the previous time (meaning there’s a 2/3 probability that it’ll be different).

In the other file, getComputerChoice is called once and the result is stored in a variable and determineWinner is called using that variable as an argument.

1 Like

Thanks!
I understand. I called the function two times, so it gives me two random numbers.
I was thinking that I called once when declaring the function and using this like a variable in the line 58.
I wasn´t considering that a declaration of a function does not call the function.

Doing this helped me to understand also:

Thanks again