Skip to content

Beginner · Strings, decisions and loops · topic 8 of 61 · 20 min

switch, the ternary operator and lookup tables

Explanation

switch compares one value against many fixed cases using ===; remember break, or execution falls into the next case. The ternary operator condition ? a : b picks one of two values in a single expression. For long fixed mappings, an object used as a lookup table is often cleaner than both.

switch: one value, many cases

When you compare one value against many fixed options, a long if / else if chain repeats the same variable again and again. switch reads the value once and jumps to the matching case. It compares with strict equality (===).

javascript
function statusMessage(status) {
  switch (status) {
    case 'PLACED':
      return 'We have your order';
    case 'SHIPPED':
      return 'On the way';
    case 'DELIVERED':
      return 'Delivered. Enjoy!';
    default:
      return 'Unknown status';
  }
}
console.log(statusMessage('SHIPPED')); // On the way

break and fall-through

Inside a function, return ends the switch. Otherwise you must write break at the end of each case. Without break, JavaScript keeps running the next case's code too. This is called fall-through. It is sometimes used on purpose to group cases.

javascript
const day = 'Sat';
let kind;
switch (day) {
  case 'Sat':
  case 'Sun':
    kind = 'weekend';   // both cases share this code on purpose
    break;
  default:
    kind = 'weekday';
}
console.log(kind); // weekend
Careful: Forgetting break is the classic switch bug: case 1: x = 'one'; case 2: x = 'two'; break; leaves x as 'two' when the value is 1. If you fall through on purpose, add a comment // falls through so readers know.

Because switch uses ===, case '1' does not match the number 1. Convert input first.

The ternary operator

The ternary (conditional) operator is the only JavaScript operator with three parts: condition ? valueIfTrue : valueIfFalse. It is an expression, so it produces a value you can store or put inside a template literal. Use it for short either/or choices.

javascript
const age = 20;
const label = age >= 18 ? 'adult' : 'minor';
const items = 1;
console.log(`You have ${items} ${items === 1 ? 'item' : 'items'}`); // You have 1 item
Tip: Do not nest ternaries more than one level. a ? b : c ? d : e is legal but hard to read. Use if / else or a lookup table instead.

|| versus ?? for defaults

Both give a fallback, but differently. a || b uses b whenever a is falsy (0, '', false…). a ?? b uses b only when a is null or undefined. Pick ?? when 0 or an empty string is a valid answer.

Lookup tables: data instead of branches

When each case just maps a key to a value, store the mapping in an object and read from it. Adding a new case means adding a line of data, not a new branch of code.

javascript
const SHIPPING_DAYS = { metro: 2, city: 4, rural: 7 };
function deliveryDays(area) {
  return SHIPPING_DAYS[area] ?? 10;  // 10 for unknown areas
}
console.log(deliveryDays('city'));   // 4
console.log(deliveryDays('island')); // 10
Think of it like this: A switch is like a railway enquiry clerk who listens to your train number and searches his notes. A lookup table is like the printed timetable on the wall: you look up the row yourself, and adding a new train just means adding a row.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

switch, the ternary operator and lookup tables · 1/6

switch · ternary · lookup

In this lesson you will choose between many options with switch, the ternary operator and lookup tables.

Prefer a video by a teacher? Find free videos on “javascript switch statement ternary operator explained” on YouTube ↗

In real life: Order status on a food-delivery app

Food apps show a friendly line for each order status coming from the server. The status list is fixed and known, so a switch or a lookup table maps each code to text, with a default for any new status the app does not know yet.

javascript
const LABELS = { ACCEPTED: 'Restaurant accepted', COOKING: 'Being prepared', OUT: 'Out for delivery' };
const status = 'COOKING';
console.log(LABELS[status] ?? 'Updating…');
Prints Being prepared.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function itemsText(n) that returns "1 item" when n is 1 and "<n> items" otherwise (e.g. "0 items", "3 items"). Use the ternary operator.

Task 2 · Code · Javascript

Write a function daysInMonth(month) for a non-leap year, using switch with grouped cases (fall-through). month is 1–12. Return 31, 30 or 28, and null for anything else.

Task 3 · Code · Javascript

Write a function gstRate(category) using a lookup object: "essential" → 5, "standard" → 18, "luxury" → 28, "exempt" → 0. Unknown categories return 18. (Example rates for practice; real GST rates depend on the item.) Watch out: 0 is a real rate.

Quick quiz

Question 1

1.Which comparison does switch use?

Question 2

2.let x; switch (1) { case 1: x = 'one'; case 2: x = 'two'; break; } What is x?

Question 3

3.What is 5 > 3 ? "yes" : "no"?

Question 4

4.Why use a lookup object instead of a long switch?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which comparison does switch use?

Answer: ===

switch compares with strict equality, so case "1" does not match 1.

let x; switch (1) { case 1: x = 'one'; case 2: x = 'two'; break; } What is x?

Answer: 'two'

There is no break after case 1, so it falls through and case 2 sets x to two.

What is 5 > 3 ? "yes" : "no"?

Answer: "yes"

The condition is true, so the value after ? is chosen.

Why use a lookup object instead of a long switch?

Answer: Each new case is a line of data, not new code

Mappings stored as data are shorter and easier to change.

What happens without break at the end of a case?Related

Answer: Execution falls through to the next case

That is fall-through.

From Decisions: if, else and switch

A switch case has code but no break. What happens?Related

Answer: Compile error: control cannot fall through

C# does not allow fall-through from a non-empty case (error CS0163).

From Decisions: if, else, switch and switch expressions

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

Which type can NOT be used in a switch?Related

Answer: std::string

switch needs an integral or enum value. Use if / else if for strings.

From Operators and decisions: if, else and switch

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Strings, decisions and loops” before its exam: Loops: for, while, do…while, for…of and for…in, Loop patterns that solve real problems.
  2. Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and closures. 61 topics left in the course before the final exam.

← Previous: Decisions with if and else