Switch overview in JavaScript

Sabrina Sabsab
3 min readMay 10, 2022

--

The statement “switch” will allow us to execute code based on the value of a variable. We will be able to manage as many situations or “cases” as we want.

In this, the statement represents an alternative to using an if…else if…else. Example:

However, these two types of instructions are not strictly equivalent.

Since in a switch, each case will be linked to a specific value. Indeed, the switch statement does not support the use of superiority operators, or inferiority.

In some (rare) situations, it may be interesting to use a switch rather than an if… else if… else because this statement can make the code clear and slightly faster in its execution.

In any case, it is good to know what a switch looks like since it is a basic structure. Common to many programming languages and will therefore allow you to understand some codes using this kind of structure.

Syntax and example using the switch in JavaScript

The syntax of a switch statement will be different from that of the conditions seen so far. Here’s another example below:

The first thing to note here, is that we must provide a variable on which we will “switch”.

Then, the switch statement will be structured around boxes that are possible “cases” or “outcomes”. If the value of our variable is equal to that case; then we execute the code that is inside.

For example, the code contained in case 0: will be executed if the value contained in our variable is 0. The code contained in case 1: will be executed if the value contained in our variable is 1, etc.

Each case on a switch must end with a break statement. This statement tells the JavaScript to exit the switch.

Without a break, JavaScript would continue to test the other various cases on the switch even if a case equal to the value of the variable was found, which would unnecessarily slow down the code and could produce unwanted behaviors.

Finally, at the end of each switch, a default statement must be specified. The default is the equivalent of the else of the conditions seen above: it is used to handle all other cases and its code will only be executed if no case matches the value of the variable.

No need to use a break statement within default since default will always be placed at the end of the switch. If the JavaScript reaches the default, then it will naturally exit the switch since it no longer contains any code after default.

Again, the switch is often of no real interest compared to the use of a classic condition apart from the fact that using a switch can in some cases reduce the execution time of a script and that this structure is sometimes clearer than an if… else if… else containing dozens of else if.

--

--