Switching out your if/else statements

Mike Brisson
2 min readApr 16, 2021

--

Using the switch statement for your conditional statements can be an excellent way to organize your conditional logic. Switch statements work in a similar way but can help clean up your code when implementing many “else if” lines.

Here’s a simple if/else statement:

We pass in the variable that we are checking against, in this case “variable”. Then we need to check the value we are checking for with the keyword “case” followed by the actual value. Finally we need to use the keyword “break” at the end of each case; otherwise the code will run the next case until it reaches “break”.

Switch statements aren’t always the best choice. An example below shows a comparison with a small number of cases vs the identical if/else version:

vs

In this comparison, both options function the same. You could use either but given that we are only looking for 3 options, it might make more sense to go with the traditional route with the if/else.

Where switch statements come in handy is when there is a potential for numerous conditions to compare.

In this example, you can see how quickly the ids can add up. A switch statement make this more legible and makes short work if it needs to be added to or edited.

--

--

No responses yet