Sub topic 5
Choosing a Value with the Conditional Operator
This chapter assumes you know how truthy and falsy values work, how === compares values, and how to write if/else chains. You should also be comfortable with const, functions, and template literals.
An if statement chooses which code to run. Often you only need to choose which value to use. The conditional operator, also called the ternary operator because it takes three operands, does that in one expression:
const age = 20;
const label = age >= 18 ? "adult" : "minor";
console.log(label); // "adult"The form is condition ? valueIfTruthy : valueIfFalsy. JavaScript evaluates the condition, checks whether it is truthy, and the whole expression then takes the value of one branch.
Expression vs Statement
The main difference between ?: and if is that the conditional operator is an expression, so it produces a value. if is a statement and produces none. That decides where each one can appear.
You can put a conditional expression anywhere a value is allowed:
const items = 3;
const user = { name: "Ada", isAdmin: false };
// In a template literal
console.log(`You have ${items} ${items === 1 ? "item" : "items"}`);
// "You have 3 items"
// As a function argument
console.log(Math.max(0, user.isAdmin ? 100 : 10)); // 10
// In an object literal
const badge = { text: user.name, color: user.isAdmin ? "red" : "gray" };
console.log(badge); // { text: "Ada", color: "gray" }
// As a return value
function sign(n) {
return n > 0 ? "positive" : n < 0 ? "negative" : "zero";
}
console.log(sign(-4)); // "negative"None of these places accept an if statement. Writing them with if would mean adding a temporary variable first.
Keeping `const`
The conditional operator also lets you declare a variable with const when its value depends on a condition. Compare:
const temperature = 31;
// With if: the variable must be declared with let and reassigned
let advice;
if (temperature > 30) {
advice = "stay inside";
} else {
advice = "go outside";
}
// With the conditional operator: one const binding, assigned once
const advice2 = temperature > 30 ? "stay inside" : "go outside";
console.log(advice, advice2); // "stay inside" "stay inside"With the let version, later code could reassign advice by mistake, and if you add a branch and forget to assign in it, advice ends up undefined. The const version rules out both problems.
How Evaluation Works
The operator evaluates lazily. JavaScript first evaluates the condition and then evaluates only the branch it selects. The other branch never runs.
So a branch can safely contain an expensive call or one that would fail if the condition were false:
function loadDefault() {
console.log("loading default...");
return { theme: "light" };
}
const cached = { theme: "dark" };
const config = cached ? cached : loadDefault(); // loadDefault never runs
console.log(config.theme); // "dark"
const list = null;
const first = list ? list[0] : "none"; // list[0] is never evaluated, so no TypeError
console.log(first); // "none"The condition follows the same truthiness rules as if. You do not need to write === true, but the usual traps still apply. count ? count : "n/a" turns a valid 0 into "n/a". If only null and undefined should count as missing, test for them directly: count != null ? count : "n/a", or use ??, which the short-circuiting chapter covers.
Chaining Conditionals
The operator is right-associative. That means a ? b : c ? d : e is grouped as a ? b : (c ? d : e). Because of this, a chain reads like an else if ladder: the first true condition wins.
function sizeLabel(n) {
return n < 10 ? "small"
: n < 100 ? "medium"
: n < 1000 ? "large"
: "huge";
}
console.log(sizeLabel(5)); // "small"
console.log(sizeLabel(250)); // "large"
console.log(sizeLabel(5000)); // "huge"If you put each condition on its own line, a short chain of simple tests stays readable, and Prettier formats chains this way. Trouble starts with nesting in the middle operand:
const a = true, b = false;
// Hard to read: a conditional nested inside the "true" branch
const result = a ? b ? "both" : "only a" : "not a";
console.log(result); // "only a"This parses correctly, but the reader has to match each ? with its : by hand. If you find yourself nesting this way, rewrite it as an if chain or a small function.
Precedence Gotchas
The conditional operator has very low precedence. Only assignment, arrow functions, yield, spread, and the comma operator share its level or sit below it. Almost every other operator binds more tightly, so surrounding expressions get absorbed into the condition.
const count = 1;
// Bug: + binds tighter, so the condition is ("You have " + count === 1)
console.log("You have " + count === 1 ? "one item" : "many items");
// "many items"
// Fix: parenthesize the conditional
console.log("You have " + (count === 1 ? "one item" : "many items"));
// "You have one item"In the buggy line, "You have " + count becomes "You have 1". Comparing that string with === 1 gives false, so the whole log prints "many items" and your text vanishes without an error. Template literals avoid this because ${...} already groups the expression.
Assignment sits below the conditional, which is why const x = cond ? a : b works without parentheses. Inside the branches, an assignment or arrow function needs no parentheses in the middle operand. In the last operand it binds as far right as it can. Add parentheses whenever you aren't sure.
| Expression | Parsed as | Column | Column | Column | Column |
|---|---|---|---|---|---|
| `a + b ? c : d` | `(a + b) ? c : d` | ||||
| `a | b ? c : d` | `(a | b) ? c : d` | ||
| `x = a ? b : c` | `x = (a ? b : c)` | ||||
| `a ? b : c ? d : e` | `a ? b : (c ? d : e)` | ||||
| `a ? b : c, d` | `(a ? b : c), d` |
What Cannot Go in a Branch
Each operand must be an expression. Statements such as return, throw, break, let, or a block { ... } are syntax errors there:
function check(n) {
// return n > 0 ? "ok" : throw new Error("bad"); // SyntaxError
if (n <= 0) throw new Error("bad");
return "ok";
}
console.log(check(5)); // "ok"Object literals are expressions, so cond ? { a: 1 } : { a: 2 } is fine. Calling a function in a branch is also legal, but using the conditional only for side effects is a code smell:
const loggedIn = true;
const showDashboard = () => console.log("dashboard");
const showLogin = () => console.log("login");
// Works, but the produced value is thrown away
loggedIn ? showDashboard() : showLogin();
// Clearer: a statement for an action
if (loggedIn) {
showDashboard();
} else {
showLogin();
}Linters such as ESLint's no-unused-expressions flag the first form. A reader who sees ?: expects a value to be used.
Choosing Between `?:` and `if`
| Situation | Prefer |
|---|---|
| Pick one of two values for a variable, argument, or return | `?:` |
| Value inside a template literal or object literal | `?:` |
| Several conditions, each mapping to a simple value | Chained `?:` on separate lines, or a lookup table |
| A branch needs several statements | `if` |
| Branches perform actions rather than produce values | `if` |
| Branch must `return`, `throw`, `break`, or `continue` | `if` |
| Condition tests only for `null`/`undefined` to supply a default | `??` |
A redundant pattern to watch for is cond ? true : false. Write Boolean(cond), or just cond if it is already a boolean. In the same way, x ? x : fallback is just x || fallback.
Exercise
What does this log, and why? const n = 0; console.log("Count: " + n ? n : "none");
Show answer
It logs 0. The + operator binds more tightly than ?:, so the condition is "Count: " + n, which is the string "Count: 0". A non-empty string is truthy, so the expression evaluates to n, which is 0. To get "Count: 0", write "Count: " + (n ? n : "none"). To get "Count: none" only when n is null or undefined, write "Count: " + (n ?? "none").
Exercise
Rewrite this function as a single return statement using a chained conditional, keeping the same behavior. function fee(age) { if (age < 3) { return 0; } else if (age < 13) { return 5; } else if (age >= 65) { return 7; } else { return 12; } }
Show answer
function fee(age) { return age < 3 ? 0 : age < 13 ? 5 : age >= 65 ? 7 : 12; } Right-associativity groups this as age < 3 ? 0 : (age < 13 ? 5 : (age >= 65 ? 7 : 12)), so the conditions are tested in the same order as the original else if chain. For readability, put each condition on its own line.
Exercise
Given const list = undefined;, does const len = list ? list.length : 0; throw an error? What about const len = list.length > 0 ? list.length : 0;?
Show answer
The first does not throw. list is falsy, so only the third operand, 0, is evaluated, and list.length never runs. The second throws a TypeError because the condition list.length > 0 is always evaluated, and reading .length of undefined fails before the operator can choose a branch.