Ternary Operator in JavaScript: Simplifying Conditional Logic
What is the Ternary Operator?
The ternary operator ?: is a shorthand for a simple if...else statement, evaluating a condition and returning one of two values.
Syntax
condition ? valueIfTrue : valueIfFalse;
Example
let age = 20;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // "Adult"
When to Use It
Ternary operators are best for short, simple conditions. For multiple conditions or complex logic, if...else or switch statements are more readable.
How JavaScript Evaluates a Ternary
The ternary operator works in three small steps:
- JavaScript evaluates the condition before the
?. - If the result is truthy, it evaluates and returns the expression after
?. - If the result is falsy, it evaluates and returns the expression after
:.
Only one of the two branches runs. That matters when a branch calls a function, because the other function is never called. The condition also does not need to be a real boolean. Values such as 0, an empty string, null, undefined and NaN count as false, and almost everything else counts as true.
const items = [];
const label = items.length ? `${items.length} items` : "Your cart is empty";
console.log(label); // "Your cart is empty", because 0 is falsy
Because the ternary is an expression that produces a value, it can go places an if statement cannot: inside a template literal, as a function argument, in an object property or as the return value of an arrow function.
Practical Patterns You Will Use Often
// Inside a template literal
const qty = 1;
console.log(`You bought ${qty} ${qty === 1 ? "ticket" : "tickets"}`);
// As the body of an arrow function
const shippingFee = (total) => (total >= 500 ? 0 : 40);
// Choosing a CSS class name
button.className = isActive ? "btn btn-active" : "btn";
// Several conditions, formatted one per line
const grade =
score >= 90 ? "A" :
score >= 75 ? "B" :
score >= 60 ? "C" :
"Fail";
The last pattern chains ternaries. It reads well when each line is a simple check, as above. Once a branch needs more than one value or any extra logic, switch to if...else.
In React code you will see ternaries constantly, because JSX only accepts expressions: {isLoggedIn ? <Dashboard /> : <Login />}.
Ternary or a default-value operator?
| Goal | Best tool |
|---|---|
| Pick between two different results | cond ? a : b |
Use a fallback only for null or undefined | value ?? "default" |
| Use a fallback for any falsy value | value || "default" |
For example, count ?? 10 keeps a real count of 0, while count || 10 would replace it with 10.
Mistakes That Make Ternaries Buggy
- Operator precedence with strings.
"Status: " + isOnline ? "On" : "Off"always gives"On", because the string is joined first and a non-empty string is truthy. Write"Status: " + (isOnline ? "On" : "Off"). - Using it only for side effects.
isValid ? save() : showError();works, but anifstatement states the intention more clearly when nothing is returned. - Deep nesting on one line. Nested ternaries without line breaks become puzzles. Format them vertically or replace them with a lookup object or
switch. - Trying to put statements inside. Branches must be expressions, so
return,letorforcannot appear inside a ternary.
A simple rule: if you can read the line aloud as "if this, then that, otherwise the other" without pausing, the ternary is a good fit.
Ready to master real-world JavaScript development?
Learn JavaScript hands-on with mentor-led, live sessions.