📄 Switch off
Tags: javascript, typescript, code
Published: 2021-07-11 10:56:04

I have this personal preference to avoid _if-else_'s and _[switch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/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.

{% replit @Jokerwolf/SwitchOff %}


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!
```
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](https://perf.link/#eyJpZCI6IjR3bHk2bmhlM2V3IiwidGl0bGUiOiJGSU5ESU5HIEEgTlVNQkVSIiwiYmVmb3JlIjoiZnVuY3Rpb24gZG9TdHVmZih4KSB7XG4gIHN3aXRjaCAoeCkge1xuICAgIGNhc2UgMTpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgMjpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgMzpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgNDpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgNTpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgNjpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgNzpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgODpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgOTpcbiAgICAgIHJldHVybiBgJHt4fSR7eH1gO1xuICAgIGNhc2UgMTA6XG4gICAgICByZXR1cm4gYCR7eH1fJHt4fWA7XG4gICAgY2FzZSAxMTpcbiAgICAgIHJld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. 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.