Switch case, if else or a lookup map — A study case
This is a never ending argument between JavaScript developers. Some will say one way is good, and others will strongly prefer another. So which is considered better practice, let’s find out together, shall we?
The case — Dress up according to my mood
Assume we have a method that will take in a mood and return some clothes to wear 👚
Cool. How should we implement it? 😃
If my mood is <happy> then give me <red dress>
The straight forward way for a human brain is to use if … else
:
Well, when we need to add more moods (which is realistic, since mood
has a lot of variations), it will be kind of… crowded and repetitive 🤦♂️ :
if (mood === 'happy') // Do something
else if (mood === 'excited') // Do something
else if (mood === 'slightly optimistic') // Do something
else if (mood === 'optimistic') // Do something
else if (mood === 'gloomy') // Do something
// ...And the show continues
Repeating code is not good (remember this fellow — hidden 🐛?). Plus, reading will be a bit tiring, won’t it 😫?
How about switch
? Lets check it out.
Switch my clothes in case I don’t feel great
A bit of definition — in case anyone doesn’t remember 😬
The
switch
statement is used to1. Evaluate an expression, based on matching its value to
case
clause by using strict comparison===
2. If matched, executes code associated within the case and anything in other cases followed after— here
break
presence is important, to ensure no further code outside the case is triggered.
Great. Our code now can be rewritten as:
Notes 💣:
- The code associated within a case starts from after
:
and untilbreak
or until the nextcase
statement. - No
{}
is needed for defining code withincase
default
case is needed as a fallback when there is no match is found.- Different cases that return same value/code can be mapped together by placing
case
one after the other.
case 'happy':
case 'slightly happy':
//Code
break;
Look cleaner to read, right? However, it is not guaranteed to have less lines of code— since switch
may need break
for each case
.
On the other hand, adding more cases is definitely easier. And we can also control the order of cases for checking( CtrlX
has never been easier without the need of adding and deleting else
👍)
But what if we have more options (say > 10 😐) ? It will still look jammed — and readability will soon become a problem. And if you forgot break
by mistake, it can be ☠️. Bug 🐛 🐛 🐛 alert!
So…I know what you are thinking, is using Object literal as a lookup table better?
Map my mood and return the correct clothes
Easy peasy. Taking advantage of Object literal is always one of the cool things in JavaScript. Instead of using if..else
, switch
, we can define in advance a lookup table of clothes based on certain moods:
And upon receiving mood
, all we need to do is:
return clothesByMood[mood] || clothesByMood.normal;
Adding another mood is easy — obviously — by adding another property field, and we’re ready. And adding more mood option can be done dynamically on run-time.
Or if you like it to be more fancy, you can consider the use of Map
That sounds sweet, doesn’t it? Some (actually most) may argue that this is indeed the best code practice, due to the amount of code lines, the cleanliness, the fact that it embraces Object literal, or even due to the fact it allows us to combine inline function with =>
from ES6.
In fact, sweet doesn’t always mean really the best option (too much sugar can give you diabetes also 😁). There are several things here to consider:
- A fallback if
mood
doesn’t exit in this map can’t be defined directly just by usingdefault
, like inswitch
, or by usingelse
inif
. - The actual amount of code lines saved sometimes is not that significant. Mostly reduced here are the repetitive of
else if
,case...break...
and nothing else. - Object takes memory. While using
switch
,if...else
does not require any additional memory. Hmm, talk about memory efficiency 🙄 - Sometimes it’s a must to do extra check
hasOwnProperty
. - What if some cases need to return or use exact same set of code or value? Or reuse some other mood’s mapped value (such as the case of
optimistic
is an extension oflightly optimistic
— which means it may use the same clothes fromlightly optimistic
and adds a few more items.) - Name convention. Not everyone is a master of naming Objects nicely (not me for example 😆)
One more thing —we always assume it works faster using Object literal. Is it actual the case?
A JsPerf test
The result surprised me, to be honest. The test was done with 10 different cases for comparing, value from 1 to 10 accordingly. And the result?
switch
is actually the fastest (in Chrome) and arguably faster in Firefox and Safari compared to if..else
Conclusion
Most will think switch
is not syntactic sugar, if...else
is ok but using lookup table by Object literal is the best when it comes to a lot of cases matching.
However, there is no 100% ideal best practice in this case. Certainly, you need to make a good judgement yourself which to apply, depends on the nature of the problem.
For example, if... else
is definitely the best when it’s less than 3 cases (if you are using switch
or Object literal for comparing if a is b or else — you must be joking, right?). But always need to plan your code ahead by asking yourself the following:
- Is there a possibility that more cases will be added in the future? If so, you should not use
if
even if there are just couple of cases at the moment, because you will have to refactor it later. - Is there a possibility that any of cases will share the same mapped behavior/value with the other? If so, Object literal may not be ideal.
- How many cases will there be (worst case scenario 🤷♀️)? Readability is something to kill for, as always.
And again, syntactic sugar is cool, but not always the best practice. It also depends a lot on developers’ personal taste. For some switch
is more straight forward, some love the simplicity of if..else
, while the others prefer the shorter version of lookup table by Object literal (or Map) 🤷♀.
In any case, code responsibly — think of maintainability, readability for other developers, and efficiency 🤞. Happy coding everyone 😸!
I’d love to hear your thoughts in the comment section below 😺( please also be responsible in commenting, being nice is always preferable 🤟)
More on ES6:
- A big fat Arrow
- Set vs Array — What and when?
- Map vs Object — What and when?
- (…) syntax in depth
- var, let, const in depth
- Destructuring me, plz!
- A new JS string with template literals
- Let’s divide our phones into Classes
More on Data Structures:
If you like this post, don’t forget to give me a 👏 below ⏬️ . It will surely motivate me a lot 😊
If you love to read more from me, feel free to check out my articles.
If you’d like to catch up with me sometimes, follow me on Twitter | Facebook or simply visit my portfolio website.