Rock Paper Scissors project


It works pretty well but sometimes I got undefined on my console. Can anyone tell me why is that happen?

That can happen if it evaluates all three of your conditions without any of them being true. That’s possible because you are generating a new random number each time, so there’s a chance there isn’t a match. What you should do instead is generate the random number at the start of your function and assign it to a variable, then use that variable to compare it to the numbers. Doing it this way means that it will always find a match.

Also, to answer your question specifically, you get undefined sometimes because if none of your if conditions end up being true, then none of your return statements are used. JavaScript will use undefined automatically.

1 Like

What do you mean none of my if statement being true? I thought it’s generating one number among 0, 1, 2 and I set specific output of each numbers… Then how there supposed be a false statement?

Each time JavaScript encounters Math.floor(Math.random() * 3) it is generating a new random number.

For example, when you compare Math.floor(Math.random() * 3) to 1 using ===, it is generating a new random number and determining if the new random number equals 1. If it equals, then it’s true. If it doesn’t equal, then it’s false. If it’s true, then it executes your return and the function is exited.

If it’s false, it goes to your next if where it’s generating a new random number again.

Since you’re generating a new random number each time instead of storing it in a variable, it’s possible that none of your if conditions will equal the value.

Here’s an example of what I mean using your code, but I’ll replace Math.floor(Math.random() * 3) with a number to simulate it executing and generating a new random number each time.

if (1 === 0) {
  return 'rock';
}
if (2 === 1) {
  return 'paper';
}
if (1 === 2) {
  return 'scissors';
}

Notice how none of these conditions are true because the ‘new random number’ never matched one of the conditions. If you generate a random number at the beginning of your function and assign it to a variable, you can use your variable to compare it to the numbers.

Click to see an example of what that would look like

Now look what would happen if we stored the random number first:

const choice = Math.floor(Math.random() * 3);

if (choice === 0) {
  return 'rock';
}
if (choice === 1) {
  return 'paper';
}
if (choice === 2) {
  return 'scissors';
}

The number is generated once so we don’t have to worry about the value changing for each condition and for none of them to be true. We know 100% that one will match.

3 Likes