Rock, paper, or scissors switch statement

So I am doing the rock, paper scissor challenge in Javascript and in the video lesson the person ends up using a switch statement for the getComputerChoice function. He writes it similar to this with no breaks…

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

We learned to write it like this, with breaks…

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

I think I understand why there is not default, since you only have 3 choices and no need for the default. Is it the same with the breaks that would normally be there? There is no worry for the code to error out since it is generating 0,1, or 2? Is that best practice or should the breaks always be there? Just trying to understand the syntax and reason why.

Thanks

The break statement essentially tells the switch to stop searching, if you leave it out the next case will be evaluated. The break is not needed here because return statements stop the execution of the function - the value will be returned and the rest of the code in the function will not be executed. So it’s like a pseudo break.

I think you’re right about the default, there is nothing to be done if it doesn’t evaluate to any of the 3 choices and in theory it should never come the default case. But it probably would be a good idea to put a log statement in default - in case something does go funky.

Not sure about best practice since I’m still learning myself :slightly_smiling_face: hopefully someone more experienced can shed some light on that.

3 Likes