Absolutely not evil. In fact, it's pure, and if-then-else isn't.
In functional languages like Haskell, F#, ML etc., it's the if-then-else statements that are considered evil.
The reason for this is that any "action" like an imperative if-then-else statement requires you to separate a variable declaration from its definition, and introduces state to your function.
For instance, in the following code:
const var x = n % 3 == 1
? Parity.Even
: Parity.Odd;
vs.
Parity x;
if (n % 3 == 1)
x = Parity.Even;
else
x = Parity.Odd;
The first one has two advantages aside from being shorter:
x
is a constant, and so offers much fewer chance of introducing bugs, and can potentially be optimized in ways the second could never be.
- The type is made clear by the expression, so the compiler can effortlessly infer that
x
needs to be of type Parity
.
Confusingly, in functional languages, the ternary operator is often called if-then-else. In Haskell, you might say x = if n mod 3 == 1 then Odd else Even
.