Chaining Ternary Operators in JavaScript Tutorial
Chaining ternaries can replace else if chains in one expression. Learn the pattern, formatting rules, and when chaining helps vs when it hurts readability.
Chaining ternary operators lets you write else if logic as a single expression. Instead of multiple if statements, you connect ternaries so each : leads into the next condition.
const score = 78;
const grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F";
console.log(grade); // "C"This chain reads like an else if: "If 90 or above, A. Otherwise, if 80 or above, B. Otherwise, if 70 or above, C. Otherwise, F." The formatting makes the logic scannable.
How Chaining Works
Stripped of any specific condition, a chained ternary is really just one ternary nested inside the false branch of another, repeated as many times as you need. A chained ternary follows this structure:
condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: fallbackValueEach ? introduces a new condition and its matching value. Each colon either leads to the next condition or, at the end, provides the final fallback.
JavaScript evaluates this left to right:
- Check condition1. If true, return value1 and stop.
- Otherwise, check condition2. If true, return value2 and stop.
- Otherwise, check condition3. If true, return value3 and stop.
- If nothing matched, return fallbackValue.
Formatting Makes the Difference
The difference between a readable chain and a mess is formatting. Compare:
// Unreadable: everything on one line
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
// Readable: each condition on its own line, colons aligned
const grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F";The second version mirrors the visual structure of an else if chain. Each line is one condition and one outcome, and the final colon holds the fallback.
When Chaining Beats else if
A chained ternary is an expression, which means it works in places where if statements cannot go:
Inside a return statement
// Chained ternary: direct return
function getTicketPrice(age) {
return age < 5 ? "Free"
: age < 13 ? "$8"
: age < 65 ? "$15"
: "$10";
}The equivalent with if needs early returns instead of a single expression, since a plain if statement cannot produce a value on its own:
// if/else: needs a variable and multiple lines
function getTicketPrice(age) {
if (age < 5) return "Free";
if (age < 13) return "$8";
if (age < 65) return "$15";
return "$10";
}Both are readable. The ternary version puts the entire logic in one expression. The if version uses early returns. Choose the style that fits your codebase.
Inside JSX or template literals
In React, you cannot write if statements inside JSX, but a chained ternary works because it is an expression:
<div className={
status === "online" ? "green"
: status === "away" ? "yellow"
: status === "offline" ? "gray"
: "black"
}>As a const initializer
A chained ternary also fits naturally into a const declaration, since the whole assignment happens in one step:
const direction = key === "ArrowUp" ? "up"
: key === "ArrowDown" ? "down"
: key === "ArrowLeft" ? "left"
: key === "ArrowRight" ? "right"
: null;Using const with a chained ternary means the variable is assigned once and never changes, which is cleaner than a let variable that gets reassigned inside an if chain.
When to Stop Chaining
The limit is readability, not syntax. Here are the warning signs:
- More than three levels: if you have four or more
?operators, switch to if/else if or switch. - Complex conditions: if each condition is more than a simple comparison, the chain becomes hard to parse.
- Mixed logic: if some branches do more than return a value (function calls, object mutations), use if/else.
// Too much: hard to scan, easy to misread
const message = isError ? (code === 404 ? "Not Found" : code === 500 ? "Server Error" : "Unknown Error") : isPending ? "Loading..." : isSuccess ? "Done" : "Idle";Splitting the outer conditions into if/else if while keeping the small inner ternary makes the structure much easier to scan:
// Better as if/else if
let message;
if (isError) {
message = code === 404 ? "Not Found" : code === 500 ? "Server Error" : "Unknown Error";
} else if (isPending) {
message = "Loading...";
} else if (isSuccess) {
message = "Done";
} else {
message = "Idle";
}The fix does not have to be all if/else. Notice that the inner ternary for error codes is fine as a small chain. The problem was nesting one chain inside another. For basic ternary syntax, see the ternary operator guide.
The Golden Rule
Read your chained ternary out loud. If it sounds like a clear sentence, keep it. If you trip over the logic, rewrite it.
// Reads like a sentence: good chain
const label = isEmpty ? "No items" : count === 1 ? "1 item" : `${count} items`;
// Reads like a puzzle: use if/else instead
const action = hasAdmin && !isBanned ? "promote" : hasAdmin && isBanned ? "unban" : !hasAdmin && isOwner ? "request" : "view";The first chain answers one question clearly ("what label do I show?"). The second chain mixes different variables and conditions across branches. If you need to reread a chain to understand it, rewrite it as if/else if. For more on writing clean conditional logic, see the else if chaining guide.
Rune AI
Key Insights
- Chained ternaries follow the pattern: cond1 ? val1 : cond2 ? val2 : cond3 ? val3 : fallback.
- Format with each condition on its own line and align the colons for readability.
- Stop at three levels. Beyond that, use if/else if or switch.
- Each ? is like an if and each : is like an else.
- Chained ternaries are expressions, so they work inside return, JSX, and template literals.
- When the logic is unclear on first glance, rewrite it as if/else if.
Frequently Asked Questions
How many ternaries can I chain?
Is chaining ternaries considered bad practice?
Should I use chained ternaries in every project?
Conclusion
Chaining ternary operators gives you else-if-like logic in a single expression. Format each new condition on its own line, align the colons, and stop at three levels. When the chain grows longer or the conditions become complex, switch to an if/else if chain or a switch statement. Readability always beats cleverness.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.