JavaScript Switch
JavaScript Switch statement is used to execute different set of statements based on different conditions. It is similar to If-Else statement, but excels in code simplicity and works greatly with numbers, characters and Strings.
Syntax
switch(expression){ case value_1 : // set of statements break; case value_2 : // set of statements break; default : // set of statements }
Explanation: The switch expression is evaluated and each case value is matched against it. When there is a match for a case value, the corresponding set of statements are executed.
- break statement is must, for each case block, for desired conditional execution.
- default block is executed when no case value is matched.
Examples
The following example demonstrates the usage of switch statement.
index.html
Note: Please note that there is break statement at the end of every case block. Failing to provide a break statement results in not breaking of switch statement. This makes the subsequent case blocks executed.
Following is an example demonstrating such scenario, where break is not used for case blocks in switch statement.
index.html
Conclusion
In this JavaScript Tutorial, we have learnt the syntax and working of JavaScript Switch statement with examples.