The Ternary
Operator
Master JavaScript's most concise conditional expression: write cleaner code with the ? : operator.
What is a Conditional?
Every program makes decisions. A conditional checks whether something is true or false, then runs different code depending on the result.
The if/else You Already Know
An if/else statement works, but it takes up multiple lines even for a simple assignment:
if (score >= 60) {
message = "Pass";
} else {
message = "Fail";
}
Enter the Ternary Operator
The ternary operator is JavaScript's only operator that takes three operands. It compresses an if/else into a single expression:
Anatomy of ? :
The Formal Syntax
Expression vs Statement
| Ternary (Expression) | if/else (Statement) | |
|---|---|---|
| Returns a value? | Yes | No |
| Can assign directly | Yes | No |
| Embed in template literal | Yes | No |
| Multi-line logic | Avoid | Preferred |
| Readability (complex) | Lower | Higher |
How to Apply It
Example 1: Basic Assignment
Assign a greeting based on the time of day:
const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(greeting); // "Good afternoon"
Example 2: Template Literals
Embed a ternary directly inside a template literal:
console.log(
`You have ${items} item${items === 1 ? "" : "s"} in your cart.`
);
// "You have 3 items in your cart."
Example 3: Function Returns
Use a ternary as the return value of a function:
return isMember ? 0.20 : 0.05;
}
console.log(getDiscount(true)); // 0.20
console.log(getDiscount(false)); // 0.05
Chained Ternaries
You can chain ternaries to handle multiple conditions, like an if/else if/else:
score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F";
Truthy vs Falsy Values
The condition in a ternary does not have to be a strict boolean. JavaScript coerces it. Here are the falsy values:
const display = name ? name : "Anonymous";
// "" is falsy, so display = "Anonymous"
Where to Use Ternaries
Common Mistakes
Quick Reference Cheat Sheet
| Pattern | Code | When to Use |
|---|---|---|
| Simple assignment | a ? b : c | One variable, two options |
| Inline in template | `${a ? b : c}` | Dynamic strings |
| Function return | return a ? b : c; | Short function bodies |
| Chained | a ? x : b ? y : z | 2-3 uniform conditions max |
| Avoid | a ? fn() : fn() | Side effects: use if/else |
Question 1 of 5
What does the following expression evaluate to?
\(5 > 3\) ? "yes" : "no"
Question 2 of 5
Which of the following is a valid use of the ternary operator?
Question 3 of 5
What is the value of result?
const result = 0 ? "truthy" : "falsy";
Question 4 of 5
Why can you use a ternary inside a template literal but not an if/else?
Question 5 of 5
What does this chained ternary return when \(x = 75\)?
\(x \ge 90\) ? "A" : \(x \ge 80\) ? "B" : \(x \ge 70\) ? "C" : "F"