JavaScript Switch


Using the Switch...Case Statement

The if...else if...else statement performs essentially the same thing as the switch..case statement, which is an alternative. The switch...case statement runs the block of code that corresponds to the match it finds after testing a variable or expression against a range of values.

There is a significant difference between the switch...case statement and the if...else statement. When JavaScript discovers a case clause that evaluates to true, it runs the code associated with that case clause together with all following case clauses until the conclusion of the switch block automatically. The switch statement runs line by line.

You must use a break statement after each instance to avoid this. Once the code associated with the first true case has been executed, the break statement instructs the JavaScript engine to exit the switch...case statement block.

Nevertheless, if the case or default clause is last in a switch statement, the break statement is not necessary. However it is a good programming practice to break the switch statement after the last case or default clause. If a subsequent case statement is introduced to the switch statement, it avoids a potential programming error.

The default clause, which specifies what will happen if no case fits the switch expression, is optional. In a switch statement, the default clause does not always have to come last.

Example

Preview