A One-Line If/Else
JavaScript Ternary Operator
The ternary operator picks between two values based on a condition. Perfect for short either/or expressions.
What you'll learn
- Read and write the ternary `condition ? a : b`
- Know when ternary reads better than `if`/`else` (and when not)
The ternary operator is a compact if/else that produces a
value. The shape is:
condition ? whenTrue : whenFalse
const age = 21;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult" ▶ Preview: console
The equivalent if/else works but is more code:
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
} In Template Literals
Ternaries shine inside ${ } — if doesn’t work there.
const count = 5;
const message = `You have ${count} ${count === 1 ? "item" : "items"}.`;
console.log(message); // "You have 5 items." ▶ Preview: console
Chaining Ternaries
You CAN stack them — but readability suffers fast.
const score = 78;
const grade =
score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" :
"F";
console.log(grade); // "C" ▶ Preview: console
When NOT to Use a Ternary
If either branch needs more than one statement or you’re not
producing a value, stick with if/else. Don’t twist a ternary just
to be compact.
// Bad: ternary for side effects (unreadable)
condition ? doOneThing() : doAnotherThing();
// Better:
if (condition) {
doOneThing();
} else {
doAnotherThing();
} Up Next
When you have many discrete options, switch is often clearer than a
long if/else if chain.