skip to Main Content

I get that this:

return A ? B : C

means

If A is true, return B, else return C

But how do I read this one:

return A ? B ? C : D : E

Not my code; I just need to understand it.

I’ve seen this answer/solution, but just saying "Javascript is right-associative, so you ‘resolve’ the ternaries from right to left" doesn’t seem to answer the question.

2

Answers


  1. A ? B ? C : D : E is equivalent to A ? (B ? C : D) : E.

    It parses as A ? X : E where X is B ? C : D.


    As for how to "read" it…the conditions are checked in order, but you can match conditions up with the values that occur when the condition is false in an outward-in nested rainbow manner. With the center value occurring when all conditions are true. Perhaps a diagram would help:

    A ? B ? C ? D ? ALL_TRUE : D_IS_FALSE : C_IS_FALSE : B_IS_FALSE : A_IS_FALSE
    │   │   │   │    X         │            │            │            │
    │   │   │   └──────────────┘            │            │            │
    │   │   └───────────────────────────────┘            │            │
    │   └────────────────────────────────────────────────┘            │
    └─────────────────────────────────────────────────────────────────┘
    
    Login or Signup to reply.
  2. To clarify, A ? B : C is a ternary operator. Instead of A, B, and C, we can rewrite it as:

    BOOLEAN ? EXPRESSION 1 : EXPRESSION 2

    Depending on if BOOLEAN is either TRUE or FALSE, we will return EXPRESSION 1 or EXPRESSION 2.

    A ? B ? C : D : E is a Nested Ternary. We basically have this:

    BOOLEAN 1 ? (BOOLEAN 2 ? EXPRESSION 1 : EXPRESSION 2) : EXPRESSION 3

    EXPRESSION 1 from our previous example is now (BOOLEAN 2 ? EXPRESSION 1 : EXPRESSION 2)

    So, reading it:

    When BOOLEAN 1 is TRUE, we return the nested ternary operator, and do a second evaluation (BOOLEAN 2 TRUE? return EXPRESSION 1, otherwise return EXPRESSION 2). However, if BOOLEAN 1 is FALSE, we return EXPRESSION 3

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search