Switch Statements In JavaScript

A switch statement is similar to a chain of else if statements, whereby the code can react in different ways dependent on the value of a variable. Any switch statement can be written as a chain of else if statements, but sometimes using a switch statement can make the code more clear and readable.

The code example shown below is a switch statement that logs different statements based on the value of the variable ‘a’. Let’s look at each section of this switch statement bit by bit.

The first part of the switch statements contains the variable which we wish to test the value of enclosed inside parenthesis. We don’t put a condition inside the parenthesis, just the variable name.

Then we define different cases we want to check. Each case has a value in each we want to check, the variable ‘a’ will then be checked against these values. If the case value is equal to the variable’s value inside the switch statement then the code inside the case statement will be executed. The break clause is used to prevent fall through. Fall through happens when multiple case statement’s code are executed, the break clause makes the computer ‘break out’ of the switch statement. The break clause are optional, but often forgotten.

The default case inside a switch statements works similar to else block inside if statements. The code inside the default block will be executed if none of the other case statements conditions inside the switch statement are met. In out full example, if the variable ‘a’ is not a number 1, 2, or 3 then the default block will be executed. In our example the default block does not have a ‘break’, that is because it is the last condition in the switch statement, so there is nothing left to break out of, it is optional but does not add anything to the switch statement.

The example below demonstrates fall-through. The case with the value 1 and the case with the value 2 will both be executed. This is because the variable ‘a’ has a value of 1, so the ‘case 1’ code will be executed but as there isn’t a break clause after case 1 then the next case will also be executed.

You can also combine cases together, in this example two conditions are matched to one line of code. This one line of code will be executed if the variable ‘a’ is equal to the value 1 or the value 2.

One thought to “Switch Statements In JavaScript”

Leave a Reply