Undefined Rock, Paper, Scissors step 6

Hi,
I am trying to complete step 6 of the rock, paper, scissors project. I keep getting undefined when I try to console.log(getComputerChoice()). I watched the video for that step and my code looks correct. Can anyone explain why I keep getting undefined?

onst getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock'|| userInput === 'paper'|| userInput === 'scissors'){
    return userInput;
  } else {
    console.log ('error');
  }
}

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

console.log(getComputerChoice());
console.log(getComputerChoice());

In order to trace back the perpetrator, log your variables. For example this one inside your getComputerChoice function:

console.log(randomNumber)

A switch statement should have a default case. That also helps to find the cause of an error.

1 Like

It looks like the problem is with randomNumber. I fixed the code to Math.floor(Math.random instead of the other way around, but I am still getting an error saying randomNumber is undefined.

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

That’s probably because you either inserted the console before you declared the variable or outside of the function scope. A variable declared with const is only available within the function scope and after it was declared.
But I think your initial problem is fixed now, right?

1 Like

Your code works fine for me once the random number function was fixed. What is the rest of the code doing?

Yes, that was it. Thank you!

2 Likes