When Ternaries Beat Logical &&
What you'll learn: Why ternary operators are safer than && for certain conditional rendering scenarios.
You've learned that && can bite you with falsy values like 0, and that ternaries provide explicit if-else control. But when should you prefer ternaries over &&?
The Explicit False Case
The key advantage: ternaries force you to handle both branches explicitly.
With &&, you only specify what happens when the condition is true. The false case is implicit (nothing renders). This works perfectly for simple show/hide scenarios:
{isLoggedIn && <ProfileButton />}
But what if you need different content for the false case? With &&, you'd need a second statement:
{isLoggedIn && <ProfileButton />}
{!isLoggedIn && <LoginPrompt />}
A ternary collapses this into one clear expression:
{isLoggedIn ? <ProfileButton /> : <LoginPrompt />}
Avoiding the Falsy Value Minefield
Ternaries also protect you from accidentally rendering falsy values. Remember the "zero trap":
{items.length && <ItemList />} // Renders "0" when empty!
The ternary version makes your intent crystal clear:
{items.length > 0 ? <ItemList /> : null}
No accidental 0 on screen. The false branch is explicit.
The Readability Factor
When both true and false outcomes matter to your UI logic, ternaries read like natural if-else statements. They document both cases at the point of decision.
Key Takeaway: Use ternaries when you need to render something specific for both true and false cases, or when you want to avoid the risk of falsy values accidentally appearing in your UI. They're more explicit than && at the cost of slightly more syntax.