Read This if You Hate Ternary Operators

Nathan G Bornstein - Mar 28 - - Dev Community

First things first, if you want to see the rest of the animeme banner in all of its glory, which is what more than likely drew you to this article in the first place, you can find it here.


Now that the critical and pressing matters are out of the way, please grant me a couple of minutes of your time to persuade you to fall madly, deeply in love with ternary operations (thank you, @kevinpowell)

When I first saw ternary operators, I became immediately angry. Unnecessarily angry, even. There was absolutely no reason for me to be feeling that way over some plaintext displaying on my screen. But it happened and I allowed myself to feel that way, which is usually a healthy thing. But not in this case.

To save any future programmers from this irrational behavior, I want to share a mnemonic I thought of that will hopefully make sense of what is otherwise some confusing syntax at first glance.


So here, we have a typical ternary operation:

let highest;
const num1 = 42;
const num2 = 42;

highest = num1 > num2 ? num1
    : num1 < num2 ? num2
    : num1;
Enter fullscreen mode Exit fullscreen mode

The way that I choose to see this expression is quite a literal one. Whenever I see that question mark after an expression, I read it as if someone was asking a question:


Is num1 greater than num2?

Oh, it isn't? Well then, is num1 less than num2?

That's still not true?? Hmmm, well then that only leaves me with one option, which is that num1 and num2 must be equivalent to each other!

Therefore, highest will be assigned to num1 (or num2, your call).


While this may seem pretty silly if you've already made peace with ternary operations, I really wish someone would've explained it to me in this way when I first came across them.

Another important thing about ternary operators to keep in mind, is that syntax formatting is everything. Much like the way I structured the ternary operator above, it really helps with readability when it's organized as such. It's pretty similar to how switch cases are formatted, when you think about it.

There's no hard and fast rule about how a ternary should be structured, but as long as you're separating out each expression on a new line, you should be pretty good.


That's all I have for this one. I hope it was a step-forward in seeing the beauty of ternary operators if you've harbored any resentment towards them in the past. They can be a beautiful thing!

~~ <3

. . . . . . . . . . . . .