Ternary Operators – Why bother?

A ternary operator is basically a short form for a conditional (if..else) statement. The syntax is “condition ? result1 : result2″. If the condition is met, then go with result1; otherwise go with result2. Here is what one looks like in JavaScript:

var annoying = true;
(annoying === true) ? alert("Yup, annoying") : alert("Not annoying");

The above will alert “Yup, annoying” because annoying resolves as true. This simplified example is annoying to read already. But with more logic and slightly more abstract variables (or god forbid, functions!) and you get a mess to read.

Assuming the code is meant to be read by anyone… even yourself a year after you’ve written it… this is much easier to scan:

var annoying = true;

if(annoying === true) { // or simply "if(annoying) { ... }"
  alert("Yup, annoying");
} else {
  alert("Not annoying");
}

Why do people use the ternary operator? For compiled languages there is no net benefit. For interpreted languages you can save a few bytes in characters. And if you run your JavaScript application through a minifier that converts to ternary operators, you gain nothing.

I can only think of two reasons: 1. Your brain is so familiar and comfortable with ternary operators that they scan just as easily as a conditional using if..else and it doesn’t occur to you that other people might knit their brows together while reading your code; 2. You want to seem clever.

Neither of these are good reasons to sacrifice code readability. So please, for the sake of the rest of us… just don’t do it.

Leave a Reply