Why does my rock/paper/scissors game always choose paper?

Hi all,

I’m working on the rock/paper/scissors exercise:
https://www.codecademy.com/courses/introduction-to-javascript/projects/rock-paper-scissors-javascript

I decided to have a go with an if/else statement for the computer to make its choice:

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

console.log(getComputerChoice());

But running the getComputerChoice function always returns paper!

I think it’s because I used a let for the random number rather than a const - but using a const gives me errors in my if statements.

Using a switch statement avoids all of this, but to learn more, I’d love to know where I’m going wrong with my if/else control flow.

Cheers!

That we always get paper suggest that if (randomNumber = 0) is considered false, what happens if we make our random number less random:

  //let randomNumber = Math.floor(Math.random() * 3); 
  randonNumber = 0;
  if (randomNumber = 0) {
    return 'rock';
  } else if (randomNumber = 1) {
    return 'paper';
  } else if (randomNumber = 2) {
    return 'scissors';
  }

now surely we should see rock, and we still don’t.

Which would tell us something goes horrible wrong with the “comparison”. You see it?

hint: The condition seems to take the first truthy value.

I think the issue is that you need to use === for comparison. The single equal sign (=) is for assigning variables. So try to change the comparisons to something like: (randomNumber === 0). The error message you are getting with a const is because JS think that you are trying to reassign the const. Yes, I have done this mistake a few times too…

OK - I understand those responses - thanks.

However…

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

Only returns rock! Now I’m confused!

Got it. I’d put the multiple in the wrong place, so my random number statement was always returning 0.

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

works just fine.

2 Likes