Switch case, if else or a lookup map — A study case

Maya Shavin
Frontend Weekly
Published in
7 min readDec 11, 2018
Credit by VectorStock — Select clothes based on mood

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 👚

dressUp() — to help you decide what to wear without thinking

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 to

1. 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.

A sample flow diagram of switch

Great. Our code now can be rewritten as:

Notes 💣:

  • The code associated within a case starts from after : and until break or until the next case statement.
  • No {} is needed for defining code within case
  • 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 easyobviously — 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:

  1. A fallback if mood doesn’t exit in this map can’t be defined directly just by using default, like in switch, or by using else in if.
  2. 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.
  3. Object takes memory. While using switch, if...else does not require any additional memory. Hmm, talk about memory efficiency 🙄
  4. Sometimes it’s a must to do extra check hasOwnProperty .
  5. 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 of lightly optimistic which means it may use the same clothes from lightly optimistic and adds a few more items.)
  6. 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?

Chrome vs Firefox vs Safari

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 🤟)

--

--