Sub topic 5
Choosing a Value with the Conditional Operator
This chapter assumes you already know how truthy and falsy values work, and how to write if/else statements. The conditional operator applies the same decision logic, but it produces a value instead of running a block of code.
The Working Model
The conditional operator, often called the ternary operator, is the only JavaScript operator that takes three operands:
const age = 20;
const label = age >= 18 ? "adult" : "minor";
console.log(label); // "adult"The parts read left to right:
- The condition comes before the
?. It is tested for truthiness, the same way anifcondition is. - If the condition is truthy, the whole expression evaluates to the value after
?. - Otherwise, it evaluates to the value after
:.
Only the chosen branch is evaluated. The other branch never runs, so a function call in it causes no side effects.
Expression vs Statement
An if statement cannot appear where JavaScript expects a value, but a conditional expression can. Because of that, the operator works in places if cannot reach:
const items = 1;
console.log(`You have ${items} ${items === 1 ? "item" : "items"}`);
// "You have 1 item"
const isMember = false;
const price = 50 * (isMember ? 0.9 : 1);
console.log(price); // 50
const greet = (name) => (name ? `Hello, ${name}` : "Hello, stranger");
console.log(greet("")); // "Hello, stranger"The equivalent if/else needs a let declared beforehand and an assignment in each branch. The conditional version lets you use const and keeps the decision on one line.
Chaining
The operator is right-associative, so a ? b : c ? d : e groups as a ? b : (c ? d : e). That lets you write a flat chain that mirrors an else if ladder:
function grade(score) {
return score >= 90 ? "A"
: score >= 80 ? "B"
: "C or below";
}
console.log(grade(85)); // "B"Put one condition on each line, as above, and a short chain stays readable. Past three or four branches, an if chain, a switch, or a lookup table is usually clearer.
Common Errors
| Mistake | Why it hurts | Better choice | Column | Column |
|---|---|---|---|---|
| `ok ? save() : log()` used as a statement | It hides control flow in an expression and discards the result | Use `if`/`else` | ||
| Nesting inside the `?` branch: `a ? (b ? x : y) : z` | It's hard to tell which `:` belongs to which `?` | Flatten the chain or use `if` | ||
| `x ? x : fallback` | It repeats `x` | `x \ | \ | fallback`, or `x ?? fallback` to keep `0` and `""` |
| Forgetting precedence: `"Total: " + n > 0 ? n : 0` | `+` and `>` bind tighter, so the condition becomes `("Total: " + n) > 0` | Wrap the conditional in parentheses |
Exercises
Exercise
What does this log, and why? const n = 0; console.log("Count: " + n ? "some" : "none");
Show answer
It logs "some". The + operator binds tighter than ?:, so the condition is "Count: " + n, which is the non-empty string "Count: 0". A non-empty string is truthy, so the first branch is chosen. Write "Count: " + (n ? "some" : "none") to get "Count: none".
Exercise
Rewrite this using a single const declaration: let fee; if (isWeekend) { fee = 12; } else { fee = 8; }
Show answer
const fee = isWeekend ? 12 : 8;
Exercise
A teammate writes const port = config.port ? config.port : 3000. Why might this be wrong if config.port can be 0, and what should replace it?
Show answer
0 is falsy, so a port of 0 would be replaced with 3000. Use const port = config.port ?? 3000, which falls back only when config.port is null or undefined.