How to write clean nested ternaries
You don’t have to. Leave it to Prettier.
Search online about using nested ternaries and you will see varying degrees of approvals. IMO, nested ternary expressions are compact and a better alternative to using if/else. Let us take a fictitious large if else condition:
const pageName = (index, state) => {
if (index === 0 && state === "active") {
return "Intro";
} else if (index === 0 && state === "inactive") {
return "Intro - Inactive";
} else if (index === 1) {
return "Contents";
} else {
return"Extra";
};
}
Ternary expressions can be much more compact and still maintain the same clarity:
const pageName = (index, state) =>
index === 0 && state === "active"
? "Intro"
: index === 0 && state === "inactive"
? "Intro - Inactive"
: index === 1
? "Contents"
: "Extra";
This format maintains the conditions and return values in the same relative position with a low noise to signal ratio. It takes a bit of getting used to. The good news is that if you have Prettier installed, it will automatically format it for you.
If you want an example of a deeply nested ternary, here is one: https://github.com/ramda/ramda/blob/master/source/empty.js . They have also used indentation. Which makes sense IMO. Ternary indentation is still an open issue in Prettier
Ternaries for control flow. Don’t.
If you are unable to find a functional solution to your control flow, use the imperative if/else.
if (index === 1) {
showPageOne();
} else {
showPage2();
}
A ternary like this:
index === 1 ? showPageOne() : showPage2();
is an imperative statement masked as an expression. In our React projects, we make an exception to using an expression for control flow only if they are simple such as this:
id && loadItems(id);
These are mostly inside JSX files but far and few because now you can use the optional chaining ?. operator for most cases.
book?.address?.[0]?.getCity?.()
No more:
book && book.address && book.address[0] && book.address[0].getCity && book.address[0].getCity()
Happy coding.