Nested Ternaries: When Readability Breaks
What you'll learn: You'll recognize the tipping point where nested ternaries go from clever to confusing, and when to refactor for maintainability.
The Problem with Going Too Deep
You've learned that ternaries are perfect for simple if-else rendering in JSX. But like stacking too many ingredients on a sandwich, nesting ternaries inside other ternaries quickly becomes messy and hard to follow.
A single nested ternary might be acceptable:
{isLoading ? (
<Spinner />
) : hasError ? (
<ErrorMessage />
) : (
<Content />
)}
This is borderline readable—it checks loading, then error, then shows content. But add one more condition and you've created a puzzle:
{isLoading ? (
<Spinner />
) : hasError ? (
isNetworkError ? <NetworkError /> : <GenericError />
) : hasData ? (
<Content />
) : (
<EmptyState />
)}
Now you're forcing readers to mentally parse multiple branches, tracking which condition belongs to which outcome. It's technically correct but cognitively expensive.
The Better Approach
Extract to variables before your JSX:
let content;
if (isLoading) {
content = <Spinner />;
} else if (hasError) {
content = isNetworkError ? <NetworkError /> : <GenericError />;
} else if (hasData) {
content = <Content />;
} else {
content = <EmptyState />;
}
return <div>{content}</div>;
Or move the logic to a helper function that returns the right component, keeping your JSX clean and the decision-making explicit.
Key Takeaway: If you need to re-read a ternary more than once to understand it, refactor to variables or helper functions—readability always wins over brevity.