Hacker News new | ask | show | jobs
by eugf_ 2553 days ago
I know that is a matter of taste, but nested ternaries are not straightforward to understand as the author try to convey. The example shows two nested levels, and I need to simulate the program flow for a while in my head to really understand it. Definitely not desirable for my everyday programming sessions. However, simple and short ternaries are welcomed.
5 comments

That’s true of anything you’re not used to. A traditional for loop is very confusing the first dozen times.

Simple chained ternaries like in the example really aren’t hard to reason about. They are a sequence of conditions, each followed by a `?`. The first condition that evaluates to true will return the value after the `?`. If none evaluate to true, the value after the final colon is returned.

You can chain as many ternaries as you want and follow the same simple rules to understand what they return.

EDIT: The example in the article is rather unfortunate though, as the if statement is nested in a different way than the ternary, for unclear reasons.

When formatted like this:

       result = (cond_A ? 1 :
                 cond_B ? 2 :
                 cond_C ? 3 : 
                 5)
they look quite a bit nicer than the if/else equivalent IMO.
Is everyone preferring to state these on multiple lines? With the advent of the widescreen monitor, I find we have all the more reason today to use all that extra space.

Using the example from the article, I'd refactor:

  const result = (!conditionA) ? ("Not A") : (conditionB ? "A & B" : "A");
or, since code should be simple to read:

  const result = (conditionA) ? (conditionB ? "A & B" : "A") : ("Not A");
All the parentheses' are redundant for the compiler or computer, but remind myself as a human that "const result" is not a direct statement, but a result of a conditional expression.

EDIT: 2nd set of parentheses' in 2nd expression might not be redundant.

This is actually nice because in some languages a case statement is a statement and not an expression -- so you can't assign the value easily. +1, would use this in production code :-)
And when conditions are not direct don't forget to add Lisp level of parentheses. I bet one time you will forget and everything will explode.
You need to do the same in-head simulation for the standard if, it just feels effortless due to familiarity. Note the author messed up by not using the same logic in the ternary.

    conditionA
      ? conditionB
        ? ‘A + B’
        : ‘A’
      : ‘Not A’;
> need to simulate the program flow for a while in my head to really understand it.

This is a matter of practice. It doesn’t take that many times thinking about it to understand how this works in general (it’s always the same).

I agree completely, the provided example is very confusing