The switch statement is another flow control based type of a statement.

This type of a conditional statement is always used for more than a few solutions needed in a regular code flow and therefore it is applied to more complex situations than the if statement.

As seen below, the flow direction is branched out to multiple choices, depending on the result of the expression itself:

switch (expression) {

   case value1: statament1;

     break;

   case value2: statament2;

    break;

   case value3: statament3;

    break;

   case value4: statament4;

    break;

   default: statement;

}

Therefore if the expression equals value1, the statement1 will be executed; if it equals value2, the statement2 will be executed; and so on?

The keyword break terminates the execution of the switch statement, and without it the code would fall through the next case. We can say that the break keyword is mandatory and without it the switch conditions would be meaningless.

The default keyword is used as a safety choice for the situations when expression does not evaluate to any of the previous cases; however the statement will work perfectly normal without it.

As anything else in JavaScript, the switch statement works with other values beside numbers. It is important to know, though, that the expression compares values with the identically equal operators, so "2" and 2 are not the same!

Example

The example with switch statement in JavaScript:

 

›› go to examples ››