-
Notifications
You must be signed in to change notification settings - Fork 26.8k
Closed
Labels
Description
The argument against nested ternaries is that they can make code more difficult to understand. But they can make code easier to understand if they are wielded properly. Instead of banning nested ternaries, require that they are formatted such that each line has a single condition and a single result, with the catch-all at the end:
// bad
const foo = maybe1 > maybe2
? "bar"
: value1 > value2 ? "baz" : null;
// good
const foo =
maybe1 > maybe2 ? "bar"
: value1 > value2 ? "baz"
: null;
This is similar to a switch statement that always breaks. With this pattern, it's impossible to get lost in nested contexts. Once you've ruled out a line applying to the case you're considering, you can safely forget it. It's easier to understand than the solutions provided by the style guide right now, and also saves a memory allocation.
Here are some other examples where this pattern improves code:
// bad
let result;
if (operator === ‘+’) {
result = left + right;
} else if (operator === ‘*’) {
result = left * right;
} else if (operator === ‘-’) {
result = left — right;
} else {
result = left / right;
}
// good
const result =
operator === ‘+’ ? left + right
: operator === ‘*’ ? left * right
: operator === ‘-’ ? left — right
: left / right;
- Less code.
- Prefers
constoverlet. - Avoids side effects (i.e. assigning value of variable outside block scope).
// bad
if (conditionA) {
outcome1();
} else if (conditionB) {
if (conditionC) {
outcome2();
} else {
outcome3();
}
} else {
outcome4();
}
// good
conditionA ? outcome1()
: conditionB && conditionC ? outcome2()
: conditionB ? outcome3()
: outcome4();
- Less code.
- Less cognitive load.
towc, builtbyproxy, jazzandrock, kasvtv, AmitGoenka and 3 moreSurm4davidvmckay and kasvtv