The Ternary Operator
A one-line if.
Sometimes you just want to pick between two values, depending on a condition. Writing a whole if else for that feels long. The ternary operator does it in one line.

- Pick between two values
- if else feels long
- One line
Condition, question mark, colon
Write the condition, then a question mark, then the value if it's true, then a colon, then the value if it's false. It's an expression, so you can store the result, or put it inside a template literal. Run it.
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status);
const items = 1;
console.log(`You have ${items} ${items === 1 ? "item" : "items"}.`);adult You have 1 item.
Keep it simple
Ternaries are great for short, simple choices. But don't nest them inside each other. That quickly becomes very hard to read. If there are more than two choices, use if and else if instead.
| key | value |
|---|---|
| cond ? a : b | a if true, else b |
| An expression | store or insert it |
| Good for | short choices |
| Avoid | nesting them |
Ternaries in practice
Ternaries are great inside template literals, and for picking between two small values. Here we pick a label for each score in a loop. But when there are more than two choices, nested ternaries get hard to read, and an if else chain is clearer. Run it.
const scores = [92, 45, 70];
for (const s of scores) {
const result = s >= 50 ? "pass" : "fail";
const icon = s >= 90 ? "(top score)" : "";
console.log(`${s}: ${result} ${icon}`);
}92: pass (top score) 45: fail 70: pass
Summary
The ternary operator picks between two values in one line. Keep it for simple choices. Next, switch, for many exact cases.
Key takeaways- cond ? a : b
- Great in templates
- Don't nest