In my time of being a coder, I’ve come across many different things that I really enjoy using. One of those things are switch statements.
Switch statements are a conditional statement that takes an expression and then will run a code block based on that expression. A switch statement is made up of multiple different keywords that make the statement work. Let’s look at an example of a switch statement closer to see how it works.
With this statement, we are looking are what language a greeting is in. There are a few main things I want to break down.
We declare a switch statement with the syntax switch(). In side the parentheses we put the variable or expression that we want to compare. For this example we put greeting which could be anything from “Hello” to “Привет”
In switch statement there are multiple cases. You can think of this as if an if statement has multiple “else ifs”. For the lines of code, the first line should be seen as greeting === “Hola”. The cases are always strict comparison. This means the the statement is only true if greeting is “Hola”. We then set greetingLang as “Spanish” to let the user know that the greeting was in Spanish. Then, we use “break” to leave the switch statement. If we did not have break, then everything below this case will also run. This is good if we are looking for a certain range of numbers to be caught by the switch statement.
The final part of the switch statement is “default”. The default case is what will run if there are no matches in the other cases. This case will be put last of all the cases, so it can catch those expressions that don’t exist in the switch statement.
So when should you use switch statements? There are several reasons to use switch over if-else. One of them is when multiple else-ifs are being attached to each other. Switch looks alot better then 5 else-if and makes your code looks cleaner. Another example is if you want an expression to catch in multiple checks. Without break, the switch statement will keep going with the expression its checking. So if you want multiple things to be the return value, you can do that with case statements.
Overall, I really enjoy switch statements. I think they are a valuable tool, and if you need to use them, they are really simple.