How to write clean nested ternaries

Image Source

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 {

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: . 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) {
} else {

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.


No more:

book && book.address && book.address[0] && book.address[0].getCity && book.address[0].getCity()

Happy coding.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store