by eugf_ · 7y ago · 0 comments
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.
result = (cond_A ? 1 :
cond_B ? 2 :
cond_C ? 3 :
5)
they look quite a bit nicer than the if/else equivalent IMO.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.
conditionA
? conditionB
? ‘A + B’
: ‘A’
: ‘Not A’;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).