

Stop Abusing the JavaScript Ternary Operator - karthikksv
http://karthikv.net/blog/javascript-ternary-operator

======
gruseom
On the contrary. I prefer

    
    
      for (var i = 0; i < arr.length; i++) {
        arr[i] = foo(i) ? bar(i) : baz(i);
      }
    

to

    
    
      for (var index = 0; index < array.length; index++) {
        if (foo(index)) {
          array[index] = bar(index);
        } else {
          array[index] = baz(index);
        }
      }
    

in every way, including for readability.

The example is trivial but instructive. Each line in the second version is
arguably more readable (in isolation) than its counterpart in the first, yet
the verbose version as a whole imposes a longer time-to-comprehension on the
reader — especially if you allow for the ability to grok idioms at a glance
that one inevitably acquires after working with a given language or system for
some time.

In my experience this argument becomes increasingly compelling as one applies
it to more complex programs. What the naive notion of "readability" fails to
account for is the compounding complexity tax of verbosity. It's a bit like
analyzing the profitability of a trading system without considering
transaction costs.

One more thing, with apologies for this being patronizing: an infatuation with
an explicit spell-everything-out standard of readability seems to be a rite of
passage on the path to programming maturity. I certainly went through it. I
remember laughing uproariously at some of P.J. Plauger's (very tight and
regular) library code years ago. I even remember shouting something like "if a
programmer working for me ever wrote code like that, I'd fire them!" I
literally did not know what I was talking about.

~~~
benaiah
He explicitly mentions that short ternary expressions like this are fine. My
rule of thumb is that if it fits comfortably on one line, it's fine to use the
ternary. (Of course, my _real_ rule of thumb is to use CoffeeScript in the
first place, but that's not always an option.)

~~~
gruseom
You're right and that's a fair point, but the argument still applies. The OP
takes it as obvious that his rewritten jQuery snippet is better. In fact it's
far from obvious, and learning the sense in which it's far from obvious is (in
my experience) an important milestone, after which one stops arguing naively
about readability and starts thinking more about the intelligibility of whole
programs. If composed ternaries are an idiom that jQuery employs to do certain
things compactly and repeatedly, that convention may well make it easier to
understand jQuery. And that is what matters—not helicoptering into arbitrary
bits of code.

In terms of lines of code—an imperfect metric but a useful one—his rewritten
example is twice as long. That may seem like a small price to pay for an
easier-to-understand snippet _in isolation_ but if you start thinking about a
complex system as a whole, and consider how complexity compounds as programs
grow, that intuition changes considerably.

(I'm done being patronizing now.)

~~~
benaiah
You make great points, and I think you're right. While I think the OP's advice
is appropriate for most situations, particularly in general JavaScript code
you have to share with other developers, jQuery's use of it is probably
entirely appropriate. I skimmed the article, and by the end, I was already
starting to grok how they were using the ternary at first glance - and, as
others have pointed out, they may have more important considerations, such as
execution speed, driving this usage.

Tangentially, I think his point about the descriptive variable names is far
more important than avoiding if...else aliases (though it's not an original
point, and the examples he shows are appropriate uses of short variable
names).

I didn't think you were particularly patronizing. If you were, then I didn't
mind.

------
daleharvey
Often a good reason to use not so pretty code is for performance reasons, you
didnt mention checking up on that so it would probably be prudent to do so
(micro optimisations are totally valid for hot paths in libraries like jquery
and browser performance is often very unintuitive)

Also if I was going to write it 'cleaner', I would find something like
<http://pastie.org/7118990> cleaner.

(but in essence I agree)

~~~
karthikksv
Do ternary operators really make much of a performance difference compared to
if-else statements? I'd imagine they're not implemented much differently when
it comes down to the instruction level (you still have the conditional
branch). If they do make a difference, I'd hope the browser makes the
optimization. Nevertheless, as you mention, this may not be the case.

~~~
marti221
It's not about the actual number of operations the code compiles down to...
it's about the number of bytes sent across the wire on initial page load.
Among the most important elements of optimizing a webpage is minimizing the
initial HTTP latency/download size. The jQuery core team is hyper-aware of all
of these performance issues, and are doing everything possible to cut the
gzipped/compressed size of their library. When you support a library that is
literally run on the majority of the internet, these small improvements make a
HUGE difference in the overall bandwidth consumption and load times of web
applications.

I agree with you that use of the ternary operator, when not used properly, can
obfuscate some code that could be simplified with if/else operators. But,
jQuery has chosen to forgo readability for performance (and for good reason
IMO).

