What good is a ternary

Uri Valevski
1 min readMay 6, 2023

--

A code review issue — why should you prefer a ternary over an if-else block?

A ternary lets you replace this kind of pattern:

const f = (x) => {
if (x > 3) {
return 'big';
} else {
return 'small';
}
}

With this:

const f = (x) => {
return x > 3 ? 'big' : 'small';
}

But why is that better?

Why was ternary even introduced if you can achieve the same with a normal if?

The common reason is visual noise and repetition. For example the return here repeats twice.

But the more compelling reason is that it lets the reader get truth about the code free of inspection.

When we look at code we are constantly proving little theorems to ourselves. Small truths about the code we’re reading. In this case, a reader of the first code snippet would prove to themself, at some level of awareness, that if we enter the first if we will not continue execution of the function, because all paths in theif block contain a return statement.

When programming we optimize, among other things, for readability. Readability can be articulated as giving maximal information to the reader with minimal effort. A ternary is a simple way to give for free the information that all code paths return a value, and so alleviate some cognitive load from the reader.

--

--

Uri Valevski
Uri Valevski

Written by Uri Valevski

Formerly: Co-founder/CTO of hyro.ai, Googler

No responses yet