if (isA) {
return A;
} else if (isB) {
return B;
} else if (isC) {
return C;
} else {
return D;
}
is equivalent to return isA ? A : isB ? B : isC ? C : D; if (isA) {
return A;
} else if (isB) {
return B;
} else if (isC) {
return C;
} else {
return D;
}
is equivalent to return isA ? A : isB ? B : isC ? C : D;Now throw in long functions with multiple arguments, and all kinds of different access patterns and this ternary starts to look like a nightmare.
let x = somelongfunc(arg, blah(etc))
? value1
: some other condition
? value2
: fallback
What I usually want is pattern matching expressions, but those are not in many languages.I almost always use grouping parentheses for this reason, unless it’s a very short single line expression. That said, if/else if/else has a different colocation problem: it puts the assignment further from the initial declaration, making its scope less obvious (unless you’re hoisting var, which is awful for its own reasons).
But it breaks peoples brains for some reason so I rarely use them professionally.
It’s really not that hard though, the ? and : are just shorthand for “else if” and “then”.
If you're ever doing this in any language with simple if() conditions, you need to refactor anyway.
Maybe, but sonarqube doesn't like it, which means I can't pass the CI pipeline, so...
return isA ? A
: isB ? B
: isC ? C
: D return isA && A || isB && B || isC && C || D;
Am I weird?