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
A ? B ? C : D : E
is equivalent toA ? (B ? C : D) : E
.It parses as
A ? X : E
whereX
isB ? 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:
To clarify,
A ? B : C
is a ternary operator. Instead ofA
,B
, andC
, we can rewrite it as:BOOLEAN
?EXPRESSION 1
:EXPRESSION 2
Depending on if
BOOLEAN
is eitherTRUE
orFALSE
, we will returnEXPRESSION 1
orEXPRESSION 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? returnEXPRESSION 1
, otherwise returnEXPRESSION 2
). However, ifBOOLEAN 1
is FALSE, we returnEXPRESSION 3