Imagine you are in need of a complex if/then routine.
No, not the below..
|
|
.. but more of..
|
|
The above program works, and shows its smartness through the message. But there obviously should be a better way than to write a thousand if’s and but’s.
That brings us to our topic of this post - switch
. Switch provides a better structured loop for evaluating multiple conditions.
Dissecting Switch
In its simplest form, switch behaves very much like if /else:
|
|
Everything just feels intuitive, except for the break
statement. So let’s dive more into it.
The actual switch
evaluates the entry condition and does nothing else. case
compares the result and executes a bunch of statements based on whether the evaluation done earlier is fulfilled with what we supplied to the specific case
.
So, ‘smart’ by itself is the condition. And, case
statements check whether ‘smart’ is equal to true
, or otherwise.
Statements following case
will be executed upon meeting the case condition. If ‘smart’ is true, a specific ‘console.log’ is executed. The chain of statements will continue to be executed until a break
statement is reached and the entire loop terminates immediately after.
If none of the case
statements hold true, default
gets executed.
Why switch?
You would have realized by now, switch is easier on the eyes. The code appears more structured and is more easy to understand than the bunch of if / else loops.
The earlier if/else loop can be rewritten as -
|
|
More advantages
-
You can
break
to your advantage1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
function whatDay(day) { let msg; switch (day) { case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": msg = "weekday"; break; case "Saturday": case "Sunday": msg = "weekend"; break; default: msg = "Welcome alien, which planet are you from?"; } return msg; } console.log(whatDay("Wednesday"));
-
Switch only needs to calculate the condition once and not during every comparison. You can, of course, do the same in
if/else
by storing the calculation in a variable and using that in your calculations.switch
just looks elegant doing the same thing. For e.g,1 2 3 4
switch ((date == today && contacts.count > 10) || (date == yesterday && contacts.count > 5 && totalcalls <= 5) { ... ... }
Conclusion
Keep calm and switch
.