Common Ternary Patterns
You'll learn how ternary operators shine in three everyday scenarios: setting default values, formatting strings, and toggling states.
Now that you know the ternary operator's syntax, let's explore where it truly shines in real code. Think of these patterns as the "greatest hits" — situations where ternaries make your code cleaner and more readable.
Setting Default Values
When a value might be falsy, use a ternary to provide a fallback:
let username = userInput ? userInput : 'Guest';
let maxItems = count ? count : 10;
This says: "Use the first value if it's truthy, otherwise use the default." It's like having a backup plan ready.
Formatting Strings
Ternaries excel at conditional string construction:
let message = isOnline ? 'Active now' : 'Offline';
let greeting = isMorning ? 'Good morning' : 'Good evening';
let label = itemCount === 1 ? 'item' : 'items';
You're choosing between two text options based on a condition — perfect for building dynamic messages.
Toggling States
Use ternaries to flip boolean values:
let isOpen = !isOpen ? true : false; // flip the state
let newStatus = currentStatus === 'active' ? 'paused' : 'active';
This pattern swaps between two states, like a light switch. Notice you're deciding "what comes next" based on "what is now."
Why These Patterns Work
All three patterns share a key trait: they're simple binary choices — pick A or B based on one condition. When you have exactly two outcomes and one test, ternaries are clearer than multi-line if/else statements. They keep related logic together on one line.
Key Takeaway: Use ternaries for defaults, simple string formatting, and state toggling — anywhere you need to pick between exactly two values based on one condition.