Ternary Pitfalls and Readability
You'll learn when the ternary operator makes code harder to read and when explicit if/else is the better choice.
The Readability Problem
While ternaries are powerful and concise, they can quickly become confusing when overused or misapplied. The goal of code is not just to work—it's to be understood by humans. A ternary that saves one line but takes five minutes to decipher is a bad trade.
When Ternaries Hurt Clarity
Complex conditions: When your condition involves multiple logical operators, wrapping it in a ternary makes it dense:
// Hard to read
let result = user && user.age >= 18 && !user.banned ? "allowed" : "denied";
// Clearer
let result;
if (user && user.age >= 18 && !user.banned) {
result = "allowed";
} else {
result = "denied";
}
Nested ternaries: While technically valid, deeply nested ternaries become nearly unreadable:
// Terrible readability
let status = score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : "F";
// Much clearer
let status;
if (score > 90) status = "A";
else if (score > 80) status = "B";
else if (score > 70) status = "C";
else status = "F";
Multiple statements: If either branch needs to do more than return a value, if/else is cleaner.
When Ternaries Excel
Use ternaries for simple, single-line decisions where both outcomes are short values:
let greeting = isLoggedIn ? "Welcome back!" : "Please log in";
Key Takeaway: Ternaries shine for simple value assignments but sacrifice readability when conditions or branches become complex—prefer explicit if/else when clarity is at risk.