Docs
3.6-Ternary-Operator
3.6 Ternary Operator
Table of Contents
- ā¢What Is the Ternary Operator
- ā¢Basic Syntax
- ā¢Comparison with if-else
- ā¢Nested Ternary Operators
- ā¢Common Use Cases
- ā¢Best Practices
- ā¢Anti-Patterns to Avoid
What Is the Ternary Operator
The ternary operator (also called the conditional operator) is JavaScript's only operator that takes three operands. It provides a concise way to write simple conditional expressions.
Why "Ternary"?
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Operator Types by Number of Operands ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā ā
ā UNARY (1 operand): !true, -5, typeof x ā
ā ā
ā BINARY (2 operands): a + b, x && y, n > 5 ā
ā ā
ā TERNARY (3 operands): condition ? valueIfTrue : valueIfFalse ā
ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Basic Syntax
Structure
condition ? expressionIfTrue : expressionIfFalse;
Visual Breakdown
condition ? valueIfTrue : valueIfFalse
ā ā ā ā ā
ā ā ā ā āāāā Returned if condition is FALSE
ā ā ā āāāāāāāāāāāāāā Separator
ā ā āāāāāāāāāāāāāāāāāāāāāāā Returned if condition is TRUE
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā Operator symbol
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā Any expression that evaluates to boolean
Basic Example
const age = 20;
const status = age >= 18 ? 'adult' : 'minor';
console.log(status); // "adult"
Execution Flow
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ā
ā age >= 18 ? "adult" : "minor" ā
ā ā ā ā ā
ā ā¼ ā ā ā
ā [true] ā ā ā
ā ā ā ā ā
ā āāāāāāāāāāāāŗ Return "adult" ā ā
ā (skipped) ā
ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Comparison with if-else
Equivalent Forms
| Ternary | if-else |
|---|---|
const result = condition ? a : b; | let result; if (condition) { result = a; } else { result = b; } |
Side-by-Side Comparison
// Using if-else
let message;
if (hour < 12) {
message = 'Good morning';
} else {
message = 'Good afternoon';
}
// Using ternary (same result)
const message = hour < 12 ? 'Good morning' : 'Good afternoon';
Key Differences
| Aspect | Ternary | if-else |
|---|---|---|
| Return Value | Always returns a value | Statement, no return |
| Use in Expressions | Yes (inside JSX, template literals) | No |
| Line Count | 1 line | Multiple lines |
| Readability | Good for simple conditions | Better for complex logic |
| Side Effects | Should be avoided | Common use case |
When Ternary Shines
// Template literals
const greeting = `Hello, ${isLoggedIn ? username : 'Guest'}!`;
// JSX (React)
return <div>{isLoading ? <Spinner /> : <Content />}</div>;
// Default values
const displayName = name ? name : 'Anonymous';
// Function arguments
console.log(isDebug ? detailedError : shortError);
Nested Ternary Operators
Multiple Conditions
You can nest ternary operators to handle multiple conditions:
const score = 85;
// Nested ternary
const grade =
score >= 90
? 'A'
: score >= 80
? 'B'
: score >= 70
? 'C'
: score >= 60
? 'D'
: 'F';
console.log(grade); // "B"
Execution Flow for Nested
score >= 90 ? "A" // Is 85 >= 90? No
: score >= 80 ? "B" // Is 85 >= 80? Yes ā Return "B"
: score >= 70 ? "C"
: score >= 60 ? "D"
: "F"
Formatting Nested Ternaries
// Style 1: Each condition on new line (most readable)
const result = condition1
? value1
: condition2
? value2
: condition3
? value3
: defaultValue;
// Style 2: Aligned colons
const type =
value === null ? 'null' : value === undefined ? 'undefined' : typeof value;
// Style 3: Inline (only for 2 simple conditions)
const size = width > 1200 ? 'large' : width > 768 ? 'medium' : 'small';
Equivalent if-else-if
// Ternary
const category =
age < 13 ? 'child' : age < 20 ? 'teenager' : age < 65 ? 'adult' : 'senior';
// Equivalent if-else-if
let category;
if (age < 13) {
category = 'child';
} else if (age < 20) {
category = 'teenager';
} else if (age < 65) {
category = 'adult';
} else {
category = 'senior';
}
Common Use Cases
1. Default Values
// Simple default
const username = inputName ? inputName : 'Guest';
// Better: nullish coalescing for null/undefined
const username = inputName ?? 'Guest';
// But ternary for truthy check
const displayCount = count ? count : 'No items';
2. Conditional Assignment
// Toggle state
const newState = isOpen ? false : true;
// Better: const newState = !isOpen;
// Choose between two values
const theme = isDarkMode ? darkTheme : lightTheme;
const discount = isPremium ? 0.2 : 0;
3. Conditional Function Calls
// Call different functions based on condition
const handler = isAsync ? handleAsync : handleSync;
// Different method calls
const result = useCache ? getCached(id) : fetchFresh(id);
4. String Interpolation
const userInfo = `Welcome, ${user ? user.name : 'Guest'}!`;
const statusText = `Status: ${isOnline ? 'Online' : 'Offline'}`;
const itemText = `${count} item${count !== 1 ? 's' : ''}`;
5. Object Property Selection
const config = {
mode: isProduction ? 'production' : 'development',
debug: isProduction ? false : true,
apiUrl: isProduction ? PROD_URL : DEV_URL,
};
6. Conditional Rendering (React/JSX)
// In JSX
return <div>{isLoggedIn ? <Dashboard user={user} /> : <LoginForm />}</div>;
// Inline conditional
return <span className={isActive ? 'active' : 'inactive'}>Status</span>;
7. Conditional Array/Object Inclusion
// Conditional array element
const items = [
'always included',
condition ? 'sometimes included' : null,
].filter(Boolean);
// Conditional object property
const user = {
name: 'John',
...(isAdmin ? { role: 'admin' } : {}),
};
Best Practices
ā DO: Keep It Simple
// Good: Simple, easy to read
const access = isAdmin ? 'full' : 'limited';
// Good: Clear intent
const greeting = isEvening ? 'Good evening' : 'Good day';
ā DO: Use for Pure Expressions
// Good: Returns a value based on condition
const displayName = user.nickname ? user.nickname : user.fullName;
// Good: Inline in template
console.log(`Found ${count} result${count === 1 ? '' : 's'}`);
ā DO: Format Nested Ternaries Clearly
// Good: Well-formatted nested ternary
const priority =
level === 'critical' ? 1 : level === 'high' ? 2 : level === 'medium' ? 3 : 4;
ā DO: Use Parentheses When Needed
// Good: Parentheses clarify precedence
const message = 'Status: ' + (isActive ? 'Active' : 'Inactive');
// Good: In complex expressions
const result = baseValue + (hasBonus ? bonus : 0) * multiplier;
Anti-Patterns to Avoid
ā DON'T: Use for Side Effects
// Bad: Side effects in ternary
isValid ? saveData() : showError();
// Good: Use if-else for side effects
if (isValid) {
saveData();
} else {
showError();
}
ā DON'T: Nest Too Deeply
// Bad: Too nested, hard to read
const result = a ? (b ? (c ? d : e) : f) : g ? h : i;
// Good: Use if-else or switch for complex logic
let result;
if (a) {
result = b ? (c ? d : e) : f;
} else {
result = g ? h : i;
}
ā DON'T: Use When if-else is Clearer
// Bad: Complex conditions
const action =
user.isAdmin && !user.suspended
? permissions.includes('delete')
? 'delete'
: 'edit'
: 'view';
// Good: if-else is clearer
let action;
if (user.isAdmin && !user.suspended) {
action = permissions.includes('delete') ? 'delete' : 'edit';
} else {
action = 'view';
}
ā DON'T: Forget It's an Expression
// Bad: Trying to use as statement
isCondition ? doSomething() : null; // Unnecessary
// Good: Just use if
if (isCondition) {
doSomething();
}
ā DON'T: Return Boolean Literals
// Bad: Redundant ternary
const isAdult = age >= 18 ? true : false;
// Good: The condition already returns boolean
const isAdult = age >= 18;
// Bad: Negation with ternary
const isMinor = age >= 18 ? false : true;
// Good: Use negation
const isMinor = age < 18;
// Or: const isMinor = !(age >= 18);
Summary
| Concept | Description |
|---|---|
| Syntax | condition ? valueIfTrue : valueIfFalse |
| Returns | Always returns one of the two values |
| Use Cases | Simple conditionals, inline expressions, JSX |
| Nesting | Possible but use carefully |
| Best For | Pure expressions without side effects |
| Avoid For | Complex logic, side effects, deep nesting |
Decision Guide
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Should I use a ternary operator? ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā ā
ā Is it a simple true/false choice? ā
ā āāā YES: Is it returning a value (not side effect)? ā
ā ā āāā YES: Use ternary ā ā
ā ā āāā NO: Use if-else ā
ā āāā NO: Does it have 2-3 conditions? ā
ā āāā YES: Consider formatted nested ternary ā
ā āāā NO: Use if-else or switch ā
ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Next Steps
After mastering the ternary operator, proceed to:
- ā¢3.7 Spread Operator - Expanding arrays and objects
- ā¢Practice using ternary in template literals
- ā¢Combine with nullish coalescing for robust defaults