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.
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