The Ternary Operator and Switch

Updated · 7 min read

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 : valueIfFalse is an expression: use it to pick a value, not to run statements.
  • Don't nest ternaries more than one level; use if or a lookup instead.
  • switch (value) compares with === against each case and runs from the match until a break.
  • Forgetting break causes 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

syntax.js
condition ? expressionIfTrue : expressionIfFalse

The 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

ternary.js▶ Try it
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));
Output
Paid in full
Late fee: $20
1 student | 3 students

When Not to Use It

A ternary is for choosing a value. If you are running actions (saving, printing, sending), use if:

avoid.js
// 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:

nested.js▶ Try it
const daysLate = 18;
const status =
  daysLate <= 0 ? "On time"
  : daysLate <= 10 ? "Grace period"
  : "Late";
console.log(status);
Output
Late

The switch Statement

Syntax

syntax.js
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

switch.js▶ Try it
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"));
Output
Credit or debit card
Bank transfer
Unknown method

Explanation: 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:

fall-through.js▶ Try it
const plan = "monthly";
let fee = 0;
 
switch (plan) {
  case "monthly":
    fee += 120;
  case "yearly":
    fee += 1300;
  default:
    fee += 0;
}
 
console.log(fee);
Output
1420

Explanation: "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:

switch-true.js▶ Try it
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");
}
Output
Late

Object 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:

lookup.js▶ Try it
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"));
Output
Paper check
Unknown method
UseWhen
Ternary ?:Choosing between two values in an expression
if...elseRunning different actions, or conditions that are ranges or combinations
switchOne value against many fixed cases where each case runs several statements
Object or Map lookupOne value mapped to another value

In Practice

The Fee Tracker's receipt line uses all three tools where each fits best:

receipt.js▶ Try it
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" }));
Output
Navika: $405 (termly) - Charged to card
Advitha: $120 (monthly) - Payment pending

Common 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".

practice.js
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
practice-solution.js▶ Try it
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));
Output
Freshman
Senior
Unknown grade

Quick check: Ternary and switch

3 questions
1What does balance > 0 ? "Owes" : "Clear" produce when balance is 0?
2How does switch compare the value with each case?
3What happens when a matching case has no break or return?

Key Takeaways

ToolShape
Ternaryconst x = cond ? a : b;
switchswitch (v) { case 1: ...; break; default: ... }
Lookupconst x = TABLE[key] ?? fallback;

Was this tutorial helpful?

Lesson 14 of 139