Switch Statement in Rock, Paper Scissors

When do I use the break; in switch statements?

when I add break after the return this block does not work. It will only work without the breaks

thank you

console.log(getUserChoice('paper'))

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

https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-javascript-syntax-part-i/modules/wdcp-22-learn-javascript-syntax-functions/projects/rock-paper-scissors-javascript

break; comes after the code in each block:

switch(randomNumber) {
  case 0:
    return 'rock';
    break;
  case 1:
    return 'paper';
    break;
  case 2:
    return 'scissors';
    break;
}

This is to separate it from others, such as when multiple cases use the same code:

function abc(x) {
  switch (x) {
    case 0:
      return "It is 0";
      break;
    case 1:
    case 2:
      return "It is 1 or 2";
      break;
    case 3:
      return "It is 3";
      break;
  }
}

console.log(abc(0));
console.log(abc(1));
console.log(abc(2));
console.log(abc(3));

It is 0
It is 1 or 2
It is 1 or 2
It is 3

2 Likes

oh I see so cases can coded that way :slight_smile: 2 or more cases then return

thank you

1 Like