How does the ternary operator work?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
condition ? valueIfTrue : valueIfFalse — the only operator in JavaScript taking three operands.
The key difference from if is that it is an expression: it produces a value, so it can go anywhere a value can.
const label = count === 1 ? "item" : "items";
// in a template literal
`You have ${count} ${count === 1 ? "item" : "items"}`
// in JSX
{isLoading ? <Spinner /> : <Content />}
// as a default in an object
const config = { retries: opts.retries ?? 3, mode: isDev ? "debug" : "prod" };
An if statement cannot appear in any of those positions, which is why the ternary is common in JSX and template strings rather than being merely a shorter if.
Where it stops helping
Nesting is where readability dies:
const s = a ? (b ? "x" : "y") : (c ? "z" : "w"); // hard to follow
One level is fine. Two is borderline. Three should be a lookup table, an early return, or a small function.
Formatting a chain across lines makes a longer sequence readable, and is a common pattern in JSX:
const status =
code >= 500 ? "server error"
: code >= 400 ? "client error"
: code >= 300 ? "redirect"
: "ok";
Do not use it for side effects
isValid ? save() : showError(); // works, but says "compute a value"
if (isValid) save(); else showError(); // states the intent
The ternary should produce something. When you are choosing an action, an if communicates better.
Related shorthands
a ?? b falls back only on null/undefined; a || b falls back on any falsy value, which discards a legitimate 0 or "". And a?.b reads safely without an explicit check. Reach for these before writing x ? x : y.
