3.5 Switch Statement

What Is the Switch Statement?

The switch statement is used to perform different actions based on different conditions. It really is similar to the a if-else statement.

Basic Structure

Use the switch statement to select one of the many code blocks to be executed.

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

Here's a run down on how this works:

Components

break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution of the code clock between the case and break.

It is not necessary to break the last case in a switch block The block breaks (ends) there anyway.

<aside> ⚠️ If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

</aside>

default Keyword

The default keyword specifies the ode to run if there is no case match.