JavaScript Switch statement is used to perform different actions based on different conditions. The statement will select a particular code to execute from several blocks of code. Switch statement can be used for decision making and is similar to if…else statement.
JavaScript Switch allows variable or expression value to change the control flow of program execution. This is impossible with else-if as the statement is more complex and the developer gets confused. Hence, switch statements would be the best option in such case.
Note: In switch case statement, fixed integer value conditions are only checked.
Flow Chart
Syntax
The JavaScript Switch statement starts with the keyword switch followed by the expression/condition represented in parentheses. Below expression is the syntax for JavaScript Switch statements.
switch(expression)
{
case value1:
//statements;
break;
case value2:
//statements;
break;
case value3:
//statements;
break;
.
.
case value n:
//statements;
break;
default :
//statements;
break;
}
In the above syntax, the expression is compared with case 1. If the condition is satisfied, then the corresponding statement gets executed until the break is reached. Otherwise (if it does not satisfy the condition), switch goes to the next case and the process continues. If neither case is satisfied, then switch executes the statements of "default case".
Note: If 'break' statement is not used in any case, then the next cases will get executed.