Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

Read This if You Hate Ternary Operators

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;

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 ternary's 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

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.