Can 'break' be omitted after 'return' in a switch statement, when used within a function body?

Having learnt that it’s necessary to use break after each case in a switch statement, I’m curious as to why it wasn’t used in either the hint for task 5 or the final walk-through video in the Rock, Paper, or Scissors Project, as follows:

/* 
If the random number generated = 0
only 'rock' is printed to the console.
*/

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

This code works fine. Can break be omitted here, because only one value would ever be returned despite the keyword return being used multiple times, once after each case? Does the first return that is executed act like break and cause the switch statement to be exited?

Do we only have to use break when the code after the matching case would otherwise allow the code after the subsequent cases to be executed as well? e.g.

/* 
If the random number generated = 0
'rock', 'paper' and 'scissors' are all printed to the console.
*/

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

The solution to this, being to use break, as follows:

/* 
If the random number generated = 0
only 'rock', is printed to the console.
*/

const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      console.log('rock');
      break;
    case 1:
      console.log('paper');
      break;
    case 2:
      console.log('scissors');
      break;
  }
1 Like

Classic rule of thumb…

break after return is unreachable.

When return is used, the function is exited immediately so we do not need to prevent the following cases being evaluated.

There may be cases where there is code following the switch, so we do not want to exit the function from a case, just execute the code and move to the statement that follows the switch.

2 Likes

… and so is this when we wouldn’t use return after case, but would use break after each case's code?.. meaning that we would exit the switch statement at the right place, but continue executing the code following the switch statement still within the function, until a return is finally reached?

1 Like

Correct. break simply means exit the switch body and resume from the next statement.

Exactly. What we do after the switch may depend on the action taken inside the switch, or it may be default code that runs in all cases before exiting the function. There need not be any return unless there is data to pass back to the caller.

2 Likes