Chapter IV · Operators & Expressions

Ternary Operator

The ternary operator (condition ? valueIfTrue : valueIfFalse) is a compact if/else that produces a value directly, making it useful anywhere an expression — not a statement — is needed.

01 What Is the Ternary Operator?

It's the only operator in JavaScript that takes three operands, hence "ternary." It exists because if/else is a statement — it can't be embedded inside another expression, like a template literal or a function argument — while the ternary operator evaluates to a value that can be used inline.

02 Simple Example

A one-line conditional value.

ternary.js
const age = 20;
const message = age >= 18 ? 'Adult' : 'Minor';
console.log(message); // 'Adult'

03 How It Works

The engine evaluates the condition before the ?. If truthy, the expression between ? and : is evaluated and becomes the result; otherwise the expression after : is evaluated instead. Only one branch ever runs — same short-circuit behavior as if/else, just expressed as a value.

04 Production Example

Inline conditional rendering text and a conditional style class — two places a statement wouldn't fit.

ui-helpers.js
function getStockLabel(quantity) {
  return quantity > 0 ? `${quantity} in stock` : 'Out of stock';
}

const buttonClass = isSubmitting ? 'button--disabled' : 'button--active';

05 Mental Model

"A fork in the road collapsed into a single sign that just tells you which path's destination to use as the answer."

06 Best Practices

  • Great for a single, simple value decision. Once branches get nested or a branch runs multiple statements, switch back to if/else for readability.
  • Avoid chaining/nesting ternaries (a ? b : c ? d : e) — it reads poorly at a glance; a small lookup object or if/else chain is usually clearer.

07 Interview Questions

Q: Why can't if/else be used inside a template literal or function argument?

if/else is a statement, not an expression — it doesn't produce a value. The ternary operator does, which is why it fits in those spots.

Q: What's the readability guideline for nested ternaries?

Avoid them — chained ternaries (a ? b : c ? d : e) are hard to scan; prefer if/else or a lookup structure once there's more than one decision.

Key Takeaway

The ternary operator is if/else as an expression — ideal for a single inline value decision, best avoided for nested or multi-statement logic.

Related Concepts