Beginner · Strings, decisions and loops · topic 8 of 61 · 20 min
switch, the ternary operator and lookup tables
Explanation
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 (===).
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 waybreak 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.
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); // weekendBecause 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.
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|| 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.
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')); // 10Need 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
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.
const LABELS = { ACCEPTED: 'Restaurant accepted', COOKING: 'Being prepared', OUT: 'Out for delivery' };
const status = 'COOKING';
console.log(LABELS[status] ?? 'Updating…');Practice (0/3 done)
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.
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for, while, do…while, for…of and for…inStrings, decisions and loops · same module
- Strings and template literalsStrings, decisions and loops · same module
- Decisions: if, else and switchC Programming (from zero to systems) · Operators and control flow
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Decisions: if, else and the ternaryJava Programming (Core to Spring Boot) · Control flow and methods
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
Questions people ask about this
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.
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).
How many branches of if / else if / else can run?Related
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.
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
- 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.
- Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and closures. 61 topics left in the course before the final exam.