A Platform To Learn To Code

JAVASCRIPT SWITCH STATEMENT



In the previous chapter we have learned that if else statement is used for decision making. We can execute a block of code when a certain condition is satisfied. switch statement is also used for the same purposes to make decisions on some conditions.

switch statement

switch statement is a conditional statement same as 'if else' statement. switch statement is a flow-control statement. It is used to control complex conditional operations. switch statement is more convenient to use in some cases, like when we have to check for a variable with hundreds of conditions.

Syntax :

switch (expression) {
    case condition_1:
        // execute this block if the condition is true...
        break;
    case condition_2:
        // execute this block if the condition is true...
        break;
    case condition_3:
        // execute this block if the condition is true...
        break;
        .
        .
        .
    default:
        // execute this block if no condition is true...
}
switch statement flow diagram

Example

Run the code

Lets see how this work:

  • First expression in switch statement is evaluated
  • Then the value found by evaluating expression is matched with condition of each case (condition can be number, string, expression, boolean)
  • if value matched then block of code for that case is executed
  • then break command breaks through the switch statement.
  • In case no condition matched then code block of default section is executed

Matching switch expression with multiple cases

In case you want to match switch expression with multiple cases to execute the same code block, for this just write all cases that you want to match without break command or expression and at the last case write your code block with break command.

Example

Run the code

Expression as condition in switch statement

In all above examples we have used numerical value as a condition but we can put anything as condition like number, string, boolean, expression etc.

Lets see an example:

Example

Run the code