You already know how to write conditions with the if operator. This construction is great for simple cases, but with too many branches, it becomes too complicated. Another operator called switch works better when you need to check multiple potential values. In this topic, you will learn how to use it.
Switch syntax
Suppose you compose an app for buying train tickets. You must show the ticket price, which varies depending on the destination. Using the if operator, you can do it like this:
let cityTo = "Paris";
if (cityTo === "Berlin") {
console.log("The price is $100");
} else if (cityTo === "Paris") {
console.log("The price is $120");
} else if (cityTo === "London") {
console.log("The price in $150");
}
As a result, you will see the text: The price is $120.
Even though there aren't too many destination options, the example above is still challenging to read and repetitive. It is not the best idea to process values with the if operator: in such cases, it is better to use the switch operator:
let cityTo = "Paris";
switch (cityTo) {
case "Berlin":
console.log("The price is $100");
break;
case "Paris":
console.log("The price is $120");
break;
case "London":
console.log("The price is $150");
break;
}
The result will be the same.
The switch statement performs specific actions depending on the variable's value. It matches the value or the expression in the parentheses (cityTo) with each case clause (Berlin, Paris, and London). If the case clause equals the expression, the corresponding operator is executed (The price is $120). For each case, the operator checks the value in strict equality using type checking.
Pay attention to the break operator at the end of each case. We will look at this in more detail later.
Processing similar cases
Assuming that the price for a ticket to London equals the price for a ticket to Rome, you can handle these cases together.
let cityTo = "Rome";
switch (cityTo) {
case "Berlin":
console.log("The price is $100");
break;
case "Paris":
console.log("The price is $120");
break;
case "London":
case "Rome":
console.log("The price is $150");
break;
}
As a result, for both London and Rome, you will see the text The price is $150 in the console.
What if you have the same price for all cities except Berlin, Paris, and London? It would be strange to list the names of all these cities with identical prices. In this situation, it is better to use the default case of the switch statement. Here's an example:
switch (cityTo) {
case "Berlin":
console.log("The price is $100");
break;
case "Paris":
console.log("The price is $120");
break;
case "London":
console.log("The price is $150");
break;
default:
console.log("The price is $90");
break;
}
If cityTo is Berlin, you will get the message The price is $100. If cityTo contains Stockholm, Athens, or Helsinki, you will see The price is $90.
This way, the default case works if a few cases don't match. The default case can be placed in any part of the switch statement, but by convention, it is better to add it to the last clause.
Break operator
You probably noticed the break keyword added at the end of each code snippet in previous examples. As a result, the program compared each expression, processed the associated block when it was true, and stopped calculating the remaining cases. The situation would be different if we forgot to insert the break keyword:
let cityTo = "Berlin";
switch (cityTo) {
case "Berlin":
console.log("The price is $100");
case "Paris":
console.log("The price is $120");
case "London":
console.log("The price is $150");
default:
console.log("The price is $90");
}
When the browser finds the correct statement, it starts executing it until it finds the break keyword. Without it, the browser will think that we don't want to stop the program, so it will continue to process other blocks of code even if they correspond to other cases. Then, the result of executing the code in the console will look like this:
The price is $100
The price is $120
The price is $150
The price is $90
Do not forget to use the break keyword after each code block to avoid errors!
Switch or if else?
The if-else in JavaScript continuously checks for a condition, and based on that condition, the code inside of if-else statement is executed. In contrast, the switch statement checks and directly jumps on the case that is to be executed. In some cases, a switch statement executes faster than an equivalent if-else ladder. This is because the compiler creates a jump table for the switch during compilation. As a result, during execution, the program just needs to choose which case to execute rather than checking if a case is satisfied. Additionally, a switch statement is easier to read for some programs than an if-else ladder. Ultimately, it is up to the developer to choose between if-else and switch statements based on their preferences to optimize the program's efficiency.
Conclusion
Now you know that it is much more preferable to use the switch statement instead of if to handle several different variable values. Switch helps avoid unnecessary repetition and makes your code easier to read. It also gives you more options for managing the handler block using the break and default keywords.