JavaScript Ternary Operator: Complete Syntax Guide
The ternary operator is a one-line if/else. Learn the syntax, when to use it for clean code, and the readability mistakes to avoid.
The ternary operator is a one-line shortcut for an if/else that returns a value. It has three parts: a condition, a value when true, and a value when false.
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"This single line does the same thing as the four-line if/else version below, since both assign the same result to status depending on the same condition:
let status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}The ternary is shorter because it is an expression: it produces a value directly, which means you can use it anywhere a value is expected.
Ternary Syntax
condition ? valueIfTrue : valueIfFalse- condition: any expression that evaluates to true or false. This goes before the
?. - ?: separates the condition from the true value. Think "then."
- valueIfTrue: the result when the condition is true.
- :: separates the true value from the false value. Think "otherwise."
- valueIfFalse: the result when the condition is false.
The entire ternary expression evaluates to a single value. That is the key difference from if/else: a ternary is an expression that produces a value, while if/else is a statement that runs code.
Practical Examples
Assigning a value based on a condition
The most common use of a ternary is picking between two values and storing the result in a variable, which is exactly the pattern shown earlier with age and status:
const isLoggedIn = true;
const buttonText = isLoggedIn ? "Dashboard" : "Log In";
console.log(buttonText); // "Dashboard"Inside template literals
Because a ternary is an expression, you can use it directly inside a template literal instead of computing a separate variable first:
const itemCount = 3;
console.log(`You have ${itemCount} item${itemCount === 1 ? "" : "s"} in your cart.`);
// "You have 3 items in your cart."This is much cleaner than computing the plural form separately. The ternary decides whether to add an "s" right where the string is built.
Inline with return statements
A ternary also works directly after return, which avoids declaring a variable just to hold the result before returning it:
function getFee(isMember) {
return isMember ? 5 : 20;
}
console.log(getFee(true)); // 5
console.log(getFee(false)); // 20Setting CSS classes in UI frameworks
A similar pattern shows up constantly in frontend code, where a ternary decides which class name to append based on component state:
const isActive = true;
const className = `nav-link ${isActive ? "active" : ""}`;
console.log(className); // "nav-link active"Ternary vs if/else: When to Use Which
| Ternary | if/else |
|---|---|
| const x = cond ? a : b; | if (cond) { x = a; } else { x = b; } |
| Returns a value | Runs code blocks |
| Good for simple value picks | Good for multi-step branches |
| One expression, one line | Multiple statements, multiple lines |
| Can be used inside other expressions | Must stand alone as a statement |
Use a ternary when both branches produce a value and the logic is simple. Use if/else when each branch does more than one thing: calling functions, updating multiple variables, or running loops.
// Ternary: clean for value assignment
const label = isEmpty ? "No data" : `${count} records`;A multi-step branch like this one needs if/else instead, since each path calls more than one function and a ternary can only ever produce a single value:
// if/else: better for multi-step branches
if (hasPermission) {
fetchData();
updateUI();
logAccess();
} else {
showAccessDenied();
redirectToLogin();
}Common Mistakes
Using a ternary when you only need an if
A ternary always requires both a ? and : branch. If you only need to act when a condition is true, use if or the AND short-circuit pattern:
// Wrong: awkward no-op with null
isReady ? startApp() : null;
// Right: use if
if (isReady) startApp();
// Also right: use && for simple one-liners
isReady && startApp();Nesting ternaries
You can nest ternaries by chaining another ternary inside the false branch, but they quickly become hard to read as more conditions stack up:
// Hard to read
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
// Better as if/else if
let grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "F";For more on nesting ternaries and how to do it safely, see the chaining ternary operators guide.
Where Ternaries Shine in Real Code
Ternaries are especially useful in React and similar frameworks where you need expressions, not statements, inside JSX:
// Inside JSX: ternary works because it is an expression
<div>
{isLoading ? <Spinner /> : <Content data={data} />}
</div>
// if/else does not work here because it is a statement, not an expressionTernaries are also clean inside array methods like map, where the callback must return a value rather than run a block of statements:
const scores = [85, 92, 60, 78];
const results = scores.map(s => s >= 70 ? "Pass" : "Fail");
console.log(results); // ["Pass", "Pass", "Fail", "Pass"]The key rule: if the ternary makes your code shorter and the intent is obvious, use it. If you pause to parse the logic, rewrite it as if/else. For the full if/else pattern, see the if else statements guide.
Rune AI
Key Insights
- The ternary operator has three parts: condition ? valueIfTrue : valueIfFalse.
- It returns a value, which makes it ideal for variable assignments.
- Always have both ? and : branches. A ternary cannot have only a true branch.
- Use ternaries for simple value picks; use if/else for multi-step branches.
- Do not nest ternaries more than one level deep.
- A ternary is an expression, so it can be used inside template literals, JSX, and console.log.
Frequently Asked Questions
What does the ? and : mean in a ternary?
Can I use a ternary without an else part?
Is the ternary operator the same as an if statement?
Conclusion
The ternary operator (? :) is a one-line conditional that returns a value. It is perfect for simple if/else assignments where both branches produce a value. Use it when it makes your code shorter and clearer. Avoid it when the condition is complex, the branches do more than return a value, or when nesting ternaries makes the logic hard to follow.
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.