The Ternary Operator and Switch
The conditional operator condition ? a : b, often called the ternary operator because it takes three operands, chooses between two values in a single expression. The switch statement compares one value against many possible cases and runs the code for the matching one. Both are alternatives to if...else: the ternary for short value choices, switch for many fixed cases. A third option, an object lookup, often beats both.
In One Minute
condition ? valueIfTrue : valueIfFalseis an expression: use it to pick a value, not to run statements.- Don't nest ternaries more than one level; use
ifor a lookup instead. switch (value)compares with===against eachcaseand runs from the match until abreak.- Forgetting
breakcauses fall-through into the next case. Return or break in every case. - For a fixed value-to-value mapping, an object or Map lookup is shorter than a
switch.
The Conditional (Ternary) Operator
Syntax
condition ? expressionIfTrue : expressionIfFalseThe whole thing produces a value, so it can go anywhere a value goes: in a variable, a template literal, a function argument, or a return.
Example
const balance = 0;
const daysLate = 12;
const status = balance > 0 ? "Owes money" : "Paid in full";
console.log(status);
console.log(`Late fee: $${daysLate > 10 ? 20 : 0}`);
const label = (count) => `${count} ${count === 1 ? "student" : "students"}`;
console.log(label(1), "|", label(3));Paid in full
Late fee: $20
1 student | 3 studentsWhen Not to Use It
A ternary is for choosing a value. If you are running actions (saving, printing, sending), use if:
// Hard to read: actions inside a ternary
isPaid ? sendReceipt() : sendReminder();
// Clear
if (isPaid) {
sendReceipt();
} else {
sendReminder();
}Nested ternaries quickly become puzzles. One level of nesting, formatted on separate lines, is the most that teams accept:
const daysLate = 18;
const status =
daysLate <= 0 ? "On time"
: daysLate <= 10 ? "Grace period"
: "Late";
console.log(status);LateThe switch Statement
Syntax
switch (expression) {
case value1:
// runs when expression === value1
break;
case value2:
case value3:
// runs for value2 or value3
break;
default:
// runs when nothing matched
}switch evaluates the expression once, compares it with each case using strict equality (===), and starts running at the first match. It keeps going until it reaches break (or return), even into the following cases.
Example
function paymentLabel(method) {
switch (method) {
case "card":
return "Credit or debit card";
case "ach":
case "bank":
return "Bank transfer";
case "check":
return "Paper check";
default:
return "Unknown method";
}
}
console.log(paymentLabel("card"));
console.log(paymentLabel("bank"));
console.log(paymentLabel("cash"));Credit or debit card
Bank transfer
Unknown methodExplanation: return leaves the function, so no break is needed. case "ach": has no code, so it falls through on purpose into case "bank":, letting two values share one result.
Fall-Through Bugs
When a case doesn't end with break or return, execution continues into the next case, whether its value matches or not:
const plan = "monthly";
let fee = 0;
switch (plan) {
case "monthly":
fee += 120;
case "yearly":
fee += 1300;
default:
fee += 0;
}
console.log(fee);1420Explanation: "monthly" matched, added 120, and then, with no break, ran the "yearly" code too. The student is charged for both plans. Each case needed a break.
switch also compares with ===, so switch ("1") never matches case 1:. Convert input values first.
switch (true) for Ranges
case values are compared with ===, so case daysLate > 10: doesn't work the way people hope... unless the switch value is true. This pattern is legal but divides teams; an if...else if chain usually reads better:
const daysLate = 18;
switch (true) {
case daysLate <= 0:
console.log("On time");
break;
case daysLate <= 10:
console.log("Grace period");
break;
default:
console.log("Late");
}LateObject Lookups: Often Better
When each case just maps one value to another, an object lookup says the same thing as a switch with less code, and the mapping becomes data you can reuse, test or load from a file:
const PAYMENT_LABELS = {
card: "Credit or debit card",
ach: "Bank transfer",
bank: "Bank transfer",
check: "Paper check",
};
function paymentLabel(method) {
return PAYMENT_LABELS[method] ?? "Unknown method";
}
console.log(paymentLabel("check"));
console.log(paymentLabel("cash"));Paper check
Unknown method| Use | When |
|---|---|
Ternary ?: | Choosing between two values in an expression |
if...else | Running different actions, or conditions that are ranges or combinations |
switch | One value against many fixed cases where each case runs several statements |
Object or Map lookup | One value mapped to another value |
In Practice
The Fee Tracker's receipt line uses all three tools where each fits best:
const PLAN_FEES = { monthly: 120, termly: 450, yearly: 1300 };
function receipt(student) {
const fee = PLAN_FEES[student.plan] ?? 0;
const discount = student.siblings > 0 ? 0.1 : 0;
let note;
switch (student.method) {
case "card":
note = "Charged to card";
break;
case "check":
note = "Check received";
break;
default:
note = "Payment pending";
}
const total = fee * (1 - discount);
return `${student.name}: $${total} (${student.plan}) - ${note}`;
}
console.log(receipt({ name: "Navika", plan: "termly", siblings: 2, method: "card" }));
console.log(receipt({ name: "Advitha", plan: "monthly", siblings: 0, method: "cash" }));Navika: $405 (termly) - Charged to card
Advitha: $120 (monthly) - Payment pendingCommon Mistakes
Missing break. Every case that doesn't return needs break.
Comparing different types in switch. switch (input) with input = "2" never matches case 2:. Convert first.
Using a ternary for actions. ok ? save() : warn() hides control flow. Use if.
Deeply nested ternaries. Two or more levels in one line are unreadable. Use a lookup or if...else if.
Practice
Challenge: Rewrite this switch as an object lookup with a default of "Unknown grade".
function band(grade) {
switch (grade) {
case 9: return "Freshman";
case 10: return "Sophomore";
case 11: return "Junior";
case 12: return "Senior";
default: return "Unknown grade";
}
}Show solution
const BANDS = { 9: "Freshman", 10: "Sophomore", 11: "Junior", 12: "Senior" };
function band(grade) {
return BANDS[grade] ?? "Unknown grade";
}
console.log(band(9));
console.log(band(12));
console.log(band(7));Freshman
Senior
Unknown gradeKey Takeaways
| Tool | Shape |
|---|---|
| Ternary | const x = cond ? a : b; |
switch | switch (v) { case 1: ...; break; default: ... } |
| Lookup | const x = TABLE[key] ?? fallback; |
Was this tutorial helpful?