The ternary operator is JavaScript's only operator that takes three operands, and it's a compact shorthand for a simple if...else statement. Instead of writing four or five lines to pick between two values, you can write one.
Basic Syntax
The syntax is condition ? valueIfTrue : valueIfFalse. The condition is evaluated, and the whole expression resolves to one of the two values depending on the result.
const age = 20;
const message = age >= 18 ? "Adult" : "Minor";
console.log(message);
// The equivalent if...else version:
let message2;
if (age >= 18) {
message2 = "Adult";
} else {
message2 = "Minor";
}
console.log(message2);
Output:
Adult
Adult
Both versions produce the same result, but the ternary is a single expression — which means it can be used directly inside a template literal, a function argument, or a JSX attribute, places where a full if...else statement isn't valid.
Using It Inline
const itemCount = 3;
console.log(`You have ${itemCount} item${itemCount !== 1 ? "s" : ""} in your cart.`);
Output:
You have 3 items in your cart.
When It Helps vs When It Hurts Readability
A single ternary for a simple either/or choice is usually clearer and shorter than a full if/else block. But chaining multiple ternaries together to handle several conditions quickly becomes hard to read:
// Avoid this — hard to scan at a glance
const grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : "F";
If you find yourself nesting ternaries more than one level deep, switch back to a proper if...else if chain or a switch statement — the small amount of extra typing pays for itself in clarity. A good rule of thumb: use the ternary when you'd say the logic out loud as "if this, then that, otherwise this" in a single breath.
