Let’s Switch it up
Swapping out if-else if-else with a Switch statement.
If you have an if-else statement with several different conditions to check for, it can get quite unruly, fast.
By using switch statements instead, you end up with something where it is easier to see what is happening.
In the switch statement, you pass in the variable to check and use case
to choose what happens when the case matches the value:
switch(num) ... case 1: ..
does the same as
if (num == 1)
If different conditions should execute the same code, you can stack them on top of each other.
(case 0 and case 1 in this example)
Compare this to using an if statement:
if (num == 0 || num == 1){}
The default
“case” is what will get executed if none of the other cases are true.
As you can probably see there is some upside to replacing if-else with a switch statement. It is way clearer what’s happening in the switch statement.
Typically done if there are 2+ conditions on a single variable.
Thank you for reading 😀