The JavaScript Ternary ?: operator
The ternary operator ?: is a compact if...else that returns one of two values: condition ? valueIfTrue : valueIfFalse. const label = ok ? "Yes" : "No". It's ideal for choosing between two values in an assignment or inside JSX; for anything complex, a full if...else stays more readable.
Overview
The ternary operator is JavaScript's only operator that takes three operands, which is where the name comes from. It's an expression form of if...else: condition ? a : b evaluates to a when the condition is truthy and b when it isn't. Because it's an expression, it returns a value, so you can drop it straight into an assignment, a template literal, or a return statement.
That's its sweet spot: choosing between two values inline. const fee = isMember ? 0 : 5 is cleaner than four lines of if...else, and it's the standard way to do conditionals inside JSX where statements aren't allowed. `You have ${n} ${n === 1 ? "item" : "items"}` handles pluralization in one breath.
The flip side is readability. Ternaries are great when short, but nesting them — a ternary inside a ternary inside a ternary — quickly becomes a puzzle. When you find yourself nesting or the branches grow long, switch back to a clear if...else or a switch. The goal is fewer lines only when it's also clearer.
Syntax
condition ? valueIfTrue : valueIfFalse
const label = age >= 18 ? "Adult" : "Minor";
const fee = isMember ? 0 : 5;
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const counts = [0, 1, 5];
const lines = counts.map(n =>
n + ' ' + (n === 1 ? 'item' : 'items')
);
document.getElementById('out').textContent = lines.join('\n');
// 0 items / 1 item / 5 items
</script>
Best practices
- Use a ternary to pick between two values in an assignment, return or template literal.
- Keep it on one short line — if it wraps or nests, prefer a full if...else.
- Avoid nesting ternaries; nested ones are hard to read and easy to misjudge.
- For one of many fixed options, a switch is clearer than a ternary chain.
Frequently asked questions
What is the ternary operator in JavaScript?
condition ? a : b returns a if the condition is truthy and b otherwise. It's a one-line if...else.