What does the break statement do in a switch statement?

Question

What does the break statement do in a switch statement?

Answer

The break statement in a switch statement tells the program to stop running after it has executed the code for the matched case, and to continue executing any code after the switch statement itself. If no break statement is used in the matching statement, the program will continue to run the next statement in the switch statement.

Example:

let myString = 'hello';

switch(myString) {
  case 'world':
    console.log(`Hello ${myString}`);
    break;

  case 'hello':
  //this case matches the expression passed to the switch statement `hello world` will be logged to the console
    console.log(`${myString} world`);

  case 'goodbye':
  //although this case does not match the expression passed to the switch statement `hello goodbye` will log to the console anyway because there was no `break` statement in the matching case
    console.log(`${myString} goodbye`);
}

if we use the return statement in switch case, do we still need to use the break statement?

3 Likes

No, because the return statement ends function execution and specifies a value to be returned to the function caller. ‘return’ thus has a similar effect to ‘break’, making it superfluous in that case.

11 Likes

Actually if you omit a break statement it will immediately jump inside the next case’s code block and execute the code there. It wont even check the case.

And that is a really good point. It speaks to what the language interpreter promises us, the programmers. If we leave out the break what is the interpreter supposed to do? The only recourse is to drop down to the next case instruction. We’re already on the instruction side of the wall. Cases don’t matter if we follow a cascade further. Only instructions matter now.

const foo = function (a) {
  switch(a) {
  case 1: 
  case 2: 
  case 3: console.log(3)
  case 4: 
  case 5: 
  case 6: console.log(6)
  case 7: 
  case 8: 
  case 9: console.log(9)
  default: console.log(10)
  }
}

Try a series of calls to foo() to see this demonstrated. Normally we would not be writing code as loose as this, but it is still valid code. We only need to be able to justify it.

3 Likes

I prefer the if instead of switch. Here is my contribution:

const toEmoticon = (emotion) => {
if (emotion === ‘shrug’) {
return ‘|{"}|’;
} else if (emotion === ‘smiley face’) {
return ‘:)’;
} else if (emotion === ‘frowny face’) {
return ‘:(’;
} else if (emotion === ‘winky face’) {
return ‘;)’;
} else if (emotion === ‘heart’) {
return ‘<3’;
} else {
return ‘|(* ~ *)|’;
}
}