Sebastian K
2 min readJan 25, 2018

--

No, no, no. I’m actually surprised to see you being the author of this article, since I always enjoyed reading your content. But I cannot agree with anything you said here.

It’s always easy to write them so that they read in a straight line, top to bottom. If you can follow a straight line, you can read a chained ternary.

They are not easy to read at all. Ternaries have the disadvantage of having an implicit meaning which requires back-tracking. You read something ? foo : bar and your brain goes:

“Something… oh there’s the question mark, so it’s a ternary expression. So I have to start interpreting again… If Something then foo, else bar!”

With nested ternaries, this backtracking has to be done more than once and costs precious time (and brain cells imho…).

Meanwhile, if expressions are more in line with our thinking process and avoid the backtracking

if(something) {
return foo;
}
return bar;

Your thought process when reading this resembles exactly what the code states!

Ternaries reduce syntax clutter. Less code = less surface area for bugs = fewer bugs.

Again, I disagree. Bugs most often stem from ambiguity and misunderstanding of code. If expressions however are explicit and thus help comprehending the code during the first read.

Ternaries don’t need temporary variables, reducing load on working memory.

How do ternaries not need temporary variables in your working memory? Here’s an example

const withTernary = ({
numberA, numberB, numberC
}) => (
numberA < 50
? numberB + numberA
: numberB < numberA
? numberB
: numberC
);

This is horrible to read and comprehend. Compare it to the if version

const withIf = ({
numberA, numberB, numberC
}) => {
if (numberA < 50) {
return numberB + numberA;
}
if (numberB < numberA) {
return numberB;
}
return numberC;
};

Again, the if expressions are more explicit and, most importantly, give an easy-to-grasp context to their inner blocks.

Ternaries have a better signal-to-noise ratio.

As with the first point, ternaries require backtracking. With if expressions, your signal is actually stronger (due to them being more explicit) and drowns out the noise.

If statements encourage side effects and mutation. Ternaries encourage pure code.

condition
? doSomethingWithSideEffectsUsingValue(value)
: doSomethingElseWithSideEffectsUsingValue(otherValue)

In what way do if expressions encourage side effects and mutation? The language may do, but not if expressions themselves. In what way do ternaries encourage pure code? Again, what you do in the actual expressions inside the ternary is your doing and allows anything the language allows you to do.

Ternaries are some nice syntax sugar and I use them in my code as well. But nested ternaries are poison when it comes to reading and understanding code.

--

--

Sebastian K

Jack of all trades — Frontend, Backend, JS, Java, Kotlin, C++