If vs Switch #
As we start learning any programming language if
is the first conditional construct that we encounter. The construct may be expresssion or a statement, either way, it is an stepping stone towards the higher power. Often, we get a choice between if
and switch
and code reviwers would not likely agree with the choice.
During my code review I consider the below to decide,
- More than 3
if/else
condition should be aswitch
- The expression evaluated has more than
1 condition
if
in case of OR & AND conditions in evaluation
There are alternatives to if
and switch
that are expressive and elegant.
Ternary operator #
Ternary operator is elegant for simple if else conditions. However, some languages to not support them and some has different syntax.
$ (condition) ? <value to be returned if true> : <value to be returned if false>
This (Tweet)[https://twitter.com/SimonHoiberg/status/1337688868527726593] response has few notable options available in Javascript.