In this tutorial, you will learn how to use the JavaScript
switch case
statement to control complex conditional operations.
switch case
statementThe switch
statement is a flow-control statement that is similar to the if else
statement. You use the switch
statement to control the complex conditional operations.
The following illustrates the syntax of the switch
statement:
switch (expression) {
case value_1:
statement_1;
break;
case value_2:
statement_2;
break;
case value_3:
statement_3;
break;
default:
default_statement;
}
Each case in the switch
statement executes the corresponding statement ( statement_1
, statement_2
,…) if the expression
equals the value ( value_1
, value_2
, …).
The break
keyword causes the execution to jump out of the switch
statement. If you omit the break
keyword, the code execution falls through the original case
into the next one.
If the expression
does not match any value, the default_statement
will be executed. It behaves like the else
block in the if-else
statement.
The following flowchart illustrates the switch
statement.
You often use a switch
statement to replace a statement that consists of complicated if else
statements chained together. Basically, the switch
statement is equivalent to the following if else
statement.
if (expression == value_1) {
statement_1;
} else if (expression == value_2) {
statement_2;
} else if (expression == value_3) {
statement_3
} else {
default_statement;
}
#javascript #programming #developer #web-development