DEV Community

Jokerwolf
Jokerwolf

Posted on

📄 Switch off

I have this personal preference to avoid if-else's and switch's whenever possible.
As you most likely already know, each case in a switch is evaluated consequently to determine if this is the case (pun intended).
Check an example bellow. We're using functions as case expressions just to have some logs.
Try passing different values to the whatsThis function and try guessing the console output before actually running the code.

If for example you pass 1, only the first case would be evaluated and the output would be:

Is this a 1?
It is 1!
Enter fullscreen mode Exit fullscreen mode

If you pass 10 - all the cases would be evaluated.
Now imagine having tens of cases to evaluate. Your code would have an O(n) complexity at least (where n is the number of cases).

How can we change this code? The most straight forward approach could be using an object literal.
Here is an example. You can see that object literal variant is faster.

Conclusion

switch is a great feature of the language. I find it useful when working with small _enum_s in TypeScript at times when I would need same return for different keys, but as a personal rule I'd start with an object literal.

Top comments (0)