Ternary Operator β Conditions in One Line
After Completing This Topic
You will understand the structure of the ternary operator, be able to replace if/else statements with a single line, and be able to judge when a ternary operator is appropriate and when it becomes difficult to read.
Transforming 4 Lines of if into 1 Line
For simple branching scenarios like "Allow access if an adult, otherwise deny":
let message;
if (age >= 18) {
message = "Access allowed";
} else {
message = "Access denied for minors";
}Using the ternary operator reduces it to a single line:
const message = age >= 18 ? "Access allowed" : "Access denied for minors";Structure: condition ? value if true : value if false
The key point is that the ternary operator returns a value. While if is a statement that doesn't return a value, the ternary operator is an expression that can be directly assigned to a variable.
Basic Patterns
// Pattern 1: Variable assignment
const status = score >= 60 ? "Pass" : "Fail";
// Pattern 2: Function argument
console.log(isLoggedIn ? "Welcome" : "Please log in");
// Pattern 3: Inside a template literal
const greeting = `${hour < 12 ? "AM" : "PM"} ${hour % 12} o'clock`;Commonality: The ternary operator is natural when you need to "choose one of two values," and that choice can be done in a single line.
Ternary in React/JSX
In React, the ternary operator is almost essential because you cannot use if statements inside JSX:
function UserGreeting({ isLoggedIn, name }) {
return (
<div>
{isLoggedIn ? (
<h1>Hello, {name}!</h1>
) : (
<button>Log In</button>
)}
</div>
);
}Inside JSX's curly braces {}, only expressions can be used. if/else is a statement and cannot be used, making the ternary operator the only inline conditional branching method.
Nested Ternary β Temptation and Pitfall
When you need to branch more than twice, you might be tempted to nest ternary operators:
// β Difficult to read
const label = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";This code works, but it will take time to interpret if you read it six months later. Even with indentation, nested ternary operators are hard to read.
Alternative 1 β if/else:
// β
Clear
let label;
if (score >= 90) label = "A";
else if (score >= 80) label = "B";
else if (score >= 70) label = "C";
else label = "F";Alternative 2 β Object mapping or function extraction:
function getGrade(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
const label = getGrade(score);Ternary vs. && (Logical AND)
In React, for cases where "render if the condition is true, otherwise render nothing":
// Ternary β explicitly return null
{isAdmin ? <AdminPanel /> : null}
// `&&` operator β more concise
{isAdmin && <AdminPanel />}&& is cleaner than the ternary operator when you don't need to render anything if the condition is false. However, there is a caveat:
// β οΈ Dangerous: If `count` is 0, "0" will be rendered on the screen
{count && <ItemList />}
// β
Safe: Explicitly convert to a boolean
{count > 0 && <ItemList />}0 is a falsy value, but React renders the number 0 on the screen. When the left side of && is a number, you should use a comparison operator to convert it to a boolean.
Difference from Nullish Coalescing (??)
// Ternary: Choose one of two values based on the condition
const display = value !== null ? value : "Default value";
// `??`: Replace only if null or undefined
const display = value ?? "Default value";?? filters only null and undefined. It passes through falsy values such as 0, "", and false. The ternary operator can use any condition, making it more versatile, while ?? is specialized for the narrow use case of providing a default value when a value is missing.
Decision Criteria
| Scenario | Recommendation |
|---|---|
| Choose one of two values to assign | β Ternary |
| JSX inline conditional rendering | β
Ternary or && |
| More than 3-way branching | β if/else or function extraction |
| Side effects (API calls, etc.) included | β if/else |
Only replacing null/undefined | β ?? operator |
Use the ternary operator when it meets all three conditions: "Two choices, one line, returns a value." If even one of these is not met, use if/else.
Key takeaway: The ternary operator is
condition ? A : Bβ an expression that chooses one of two values. If you nest it, it becomes hard to read, so revert toif/elsewhen the branching becomes more complex.