Introduction:
The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task. Using if-else statements for this purpose will be less efficient than switch case statements and also it will make the code look messy.
The switch case statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
Explanation:
- expression can be of type numbers or strings.
- Duplicate case values are not allowed.
- The default statement is optional. If the expression passed to switch does not matches with value in any case then the statement under default will be executed.
- The break statement is used inside the switch to
terminate a statement sequence.
- The break statement is optional. If omitted, execution
will continue on into the next case.