javascriptternary-operatorternary-tree

Easy way to understand nested ternary operators?


Is there a simple heuristic for understanding how to read nested ternary operators? I came across this in someone's source code and can't grok it. A simple ternary is easy:

isRed = color == 'red' ? true : false

But how do you read the following? Can I just line up the first with the last and the second with the second to last, or must I parse this into an if/else tree in my head?

var offset =
  ( hasFrozenRows )
    ? ( options.frozenBottom )
    ? ( row >= actualFrozenRow )
    ? ( h < viewportTopH )
    ? ( actualFrozenRow * options.rowHeight )
    : h
    : 0
    : ( row >= actualFrozenRow )
    ? frozenRowsHeight
    : 0
    : 0;

Retabbed, it can look like this, which is almost understandable (?)

      var offset =
        ( hasFrozenRows ) ?
          ( options frozenBottom ) ?
            ( row >= actualFrozenRow ) ?
              ( h < viewportTopH ) ?
                ( actualFrozenRow * options.rowHeight )
                :
                h
              :
              0
            :
            ( row >= actualFrozenRow ) ?
              frozenRowsHeight
              :
              0
            :
            0;

Solution

  • I think you could have more luck if you try to read it as a series of check this, if true then this, else that.

    For this, it might be easier to put the ? and : operators at the beginning of lines, and read them as if they were arrows on a flowchart, labeled "yes" and "no". e.g.:

    cond1 
      ? cond2 
        ? cond3 
          ? res1 
          : res2
        : res3
      : res4
    

    Which could be read as:

    cond1?
      yes -> is cond2 
        yes -> is cond3?
          yes -> res1 
          no -> res2
        no -> res3
      no -> res4
    

    That still doesn't make this very readable, and I agree with all the comments saying this kind of code should really be rewritten to be readable.