References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Ternary ?: operator

Operator JavaScript All modern browsers Updated
Quick answer

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

Live 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?
A compact conditional expression: condition ? a : b returns a if the condition is truthy and b otherwise. It's a one-line if...else.
When should I use a ternary instead of if...else?
When you're choosing between two values inline (an assignment or return). For side effects or complex logic, use if...else.
Can I nest ternary operators?
You can, but it gets hard to read fast. Prefer an if...else or switch when you have more than two outcomes.
Does the ternary return a value?
Yes — it's an expression, so it evaluates to one of the two values and can be assigned or returned directly.