Dave Sag
2 min readMay 26, 2020

--

Use nested ternary operators without confusion with better formatting.

Also, we don’t have to call it with foo on the fly right after defining it. Therefore, it’s much easier to read and write.

However, we shouldn’t abuse the ternary operator by nesting them like:

const foo = a ? b ? c ? 'foo' : 'bar' : 'baz' : 'qux';

The code above is hard to read because we have to put in the parentheses to delimit them ourselves in our own minds.

This is hard on our brains and so we shouldn’t have expressions like the ones above.

Your problem is not that the statement is hard to decipher, it’s that you’ve written it in a way that makes it hard to decipher. Fix this with a simple formatting trick that makes long, nested ternary operators easy to understand.

Instead of:

const foo = a ? b ? c ? 'foo' : 'bar' : 'baz' : 'qux';

Rewrite it like this:

const foo = a
? b
? c
? 'foo'
: 'bar'
: 'baz'
: 'qux';

It’s not perfect but that’s an issue of the logic, (it would also look terrible with if … else statements) but it’s readable, and pretty easy to see what’s going on.

That said however, the example you cited is not really that typical. More typical is something like:

const foo = isNaN(a)
? 'foo'
: a > 0
? 'bar'
: a < 0
? 'blerp'
: 'bleep';

This is easy to read and to reason about. It’s certainly easier to read than:

const foo = isNaN(a) ? 'foo' : a > 0 ? 'bar' : a < 0 ? 'blerp' : 'bleep';

Formatting matters, not to the interpreter, but to the human reader. Javascript is incredibly forgiving when it comes to white-space. Leverage that feature to make your code more readable and tame those unwieldy ternary operators.

--

--

Dave Sag
Dave Sag

Responses (1)