What does the break statement do in a switch statement?


#1

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`);
}