ternary operator (? :)
In JavaScript, the ternary operator (? :) evaluates a condition and returns one of two expressions: the first when the condition is truthy and the second when it’s falsy. ECMA-262 and MDN call it the conditional operator. It’s the only JavaScript operator that takes three operands.
The condition doesn’t need to be a boolean. JavaScript converts it to one, so values such as 0, "", NaN, null, and undefined select the second expression. Only the selected branch runs. Because the operator produces a value, it fits where an if statement can’t, such as in a const declaration, a function argument, or a template literal.
JavaScript Ternary Operator Syntax
The operator puts ? after the condition and : between the two branches:
<condition> ? <exprIfTrue> : <exprIfFalse>
Each branch can be another ternary or an assignment, and the whole expression evaluates to the value of the branch that runs.
JavaScript Ternary Operator Examples
Say a checkout page charges 4.99 for shipping on orders under 50 and ships larger orders for free. A ternary picks the fee in one expression:
> const subtotal = 42.5;
undefined
> subtotal >= 50 ? 0 : 4.99
4.99
The comparison returns false, so the operator skips 0 and evaluates to 4.99.
A profile header greets a signed-in user by name and shows a generic label when nobody is signed in. The ternary reads .name only when user is truthy:
> const user = null;
undefined
> user ? user.name : "Guest"
'Guest'
> user.name
Uncaught TypeError: Cannot read properties of null (reading 'name')
Because null is falsy, the first branch never runs. Reading user.name directly throws a TypeError, as the last prompt shows.
JavaScript Ternary Operator Gotchas
- Chained ternaries group from the right, so
score >= 90 ? "A" : score >= 80 ? "B" : "C"reads asscore >= 90 ? "A" : (score >= 80 ? "B" : "C")and works like anif/else ifchain. - The ternary operator has lower precedence than
+and the comparison operators, so"Paid: " + paid ? "yes" : "no"tests the non-empty string that+builds and always returns"yes". - A falsy value that’s valid data, such as
0or"", selects the second branch, socount ? count : "none"replaces a real count of0.
JavaScript Ternary Operator Use Cases
- Choosing the value of a
constbinding from a condition - Picking singular or plural wording inside a template literal
- Guarding a property read when a value might be
nullorundefined - Returning one of two values from a concise arrow function body
- Passing a conditional argument to a function call
Related Resources
Course
JavaScript Conditionals for Pythonistas
Port a sailing club's race-day call from Python to JavaScript, and learn else if chains, the conditional operator, combined conditions, range checks, and switch.
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 12, 2026