Explain it simply
Explain it simply
Picture a vending machine. Press button 1 and you get water, press 2 and you get coffee, press a number that does not exist and the screen says "invalid choice". The machine takes one number, checks it against a fixed list of options and performs the one that matches.
JavaScript's switch statement works like that machine. You hand switch (value) one value, and labels such as case "water": are the options. When no case matches, the default: branch runs. When every check is about the same single value, this reads more cleanly than a long chain of if...else if.
Problem → Why → Solution
The problem: one missing break charges the wrong fee
Imagine a shop function that picks a shipping fee by zone. The "local" zone should cost 2 dollars, yet local customers are being charged the national price of 5. No error appears anywhere, and the code looks correct at a glance.
function shippingFee(zone) {
let fee;
switch (zone) {
case "local":
fee = 2; // no break here!
case "national":
fee = 5;
break;
default:
fee = 15;
}
return fee;
}
console.log(shippingFee("local")); // 5, not 2Why does it return 5?
Once switch finds a matching case, it jumps there and keeps running every statement below it until it hits break, return or the end of the switch block. The other case labels are not walls, only markers. So after fee = 2 runs, fee = 5 runs too and overwrites it. This behaviour is called fallthrough.
Core concept: how switch really works
When switch (expression) runs, JavaScript evaluates the expression in the parentheses exactly once. It then compares the result against each case from top to bottom using strict equality (===). There is no type conversion, so switch ("1") does not match case 1:. Values from form inputs, URL queries and prompt() are always strings, which makes this a real-world bug.
As soon as a case matches, execution jumps below that label and runs the statements there. break leaves the switch immediately, and inside a function return does the same. Without either one, execution continues into the next case's code. The deliberate use of this fallthrough is grouping: writing case "sat": case "sun": back to back makes both labels share one block of code.
default runs when no case matches. It may legally appear anywhere, but by convention it goes last. Without a default, an unknown value silently does nothing, so put a clear policy in default: return a fallback value or throw an error.
switch shines when one value is checked against a small, fixed set of options such as statuses, commands or weekday numbers. For ranges such as score >= 90, if...else fits better. When each value simply maps to another value, a lookup object is shorter still.
Case values do not have to be literals. case MAX_LEVEL: or case "ad" + "min": also work, because each case expression is evaluated in turn until one matches. Most code still sticks to literals and named constants, since they keep the list of options readable at a glance.
All cases share one block
The whole switch body is a single { } block. Declaring let message in two cases throws the SyntaxError "Identifier 'message' has already been declared". Wrapping a case in braces, case 1: { ... }, gives it its own scope.
- Evaluate the expression once
- Compare each case with ===
- Jump to the first matching label
- Run downward until break/return
Case labels are entry points, not walls; only break or return stops the flow.
General pattern
switch (expression) {
case valueA:
// runs when expression === valueA
break;
case valueB:
case valueC:
// shared code for valueB and valueC
break;
default:
// runs when nothing matched
}End each case with break. Two labels written back to back share one block of code. default sits last and runs when nothing matched.
Example: turning a weekday number into a name
new Date().getDay() returns 0 for Sunday, 1 for Monday and so on up to 6 for Saturday. Using today's date would make the output depend on the day you run it, so this example wraps the switch in a function and passes fixed values. Watch the last call, which passes the string "1".
function describeDay(day) {
let dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Another day";
}
return dayName;
}
// describeDay(new Date().getDay()) would use today; fixed values keep output stable
console.log("0 -> " + describeDay(0));
console.log("1 -> " + describeDay(1));
console.log("3 -> " + describeDay(3));
console.log('"1" -> ' + describeDay("1"));Code breakdown
- Line 3
switch (day) {day is read once and compared with === against the cases below, in order.
- Lines 4-6
case 0:When day is 0, execution jumps here, sets dayName to "Sunday" and break exits the switch. Without that break, the Monday code would run next.
- Lines 13-14
default:Every value other than 0, 1 and 6 lands here. It is the last branch, so it needs no break.
- Line 16
return dayName;Hands the name chosen by the switch back to the caller.
- Line 23
console.log('"1" -> ' + describeDay("1"));"1" is a string and case 1 is a number, so === is false and the result is "Another day", not Monday.
0 -> Sunday
1 -> Monday
3 -> Another day
"1" -> Another day- Evaluate switch (day)
- Test case 0, 1, 6 with ===
- On a match, run that code and break
- With no match, run default
A case matches
dayName = "Monday"
Nothing matches
dayName = "Another day"
Grouping cases, and the lookup-object alternative
When several values must produce the same result, stack their case labels and use fallthrough on purpose. Inside a function, return makes break unnecessary because it leaves both the switch and the function. When you only map a status to a piece of text, storing the pairs in an object and falling back with ?? is shorter than a switch.
function dayType(day) {
switch (day) {
case "sat":
case "sun":
return "weekend";
case "mon":
case "tue":
case "wed":
case "thu":
case "fri":
return "weekday";
default:
return "unknown";
}
}
const statusLabels = { pending: "Waiting for payment", paid: "Preparing" };
console.log(dayType("sun"), dayType("wed"), dayType("holiday"));
console.log(statusLabels["paid"] ?? "Unknown status");
console.log(statusLabels["lost"] ?? "Unknown status");Because a lookup object is plain data, it is easy to load from a JSON file or swap out in a test. When each branch must run several statements, switch stays clearer, since packing functions into an object quickly becomes hard to read.
In real projects
Where switch shows up in real projects
In e-commerce apps, what happens to an order depends on its status: pending, paid, shipped or cancelled. Each status triggers different work, such as sending a payment reminder, packing items, emailing a tracking link or issuing a refund. With a fixed set of statuses like this, switch shows one clear branch per status. When someone adds a new "refunded" status to the database, the default branch should log it or raise an error instead of silently ignoring it.
Command-line tools route a typed command such as start, stop or status through a switch. Reducer functions in state libraries like Redux commonly switch on action.type, and keyboard-shortcut handlers often switch on event.key values such as "ArrowUp" or "Escape". In all of these, a single value is being tested and the possible options are known in advance.
Common mistakes
Common mistakes
1. Forgetting break
As with shippingFee in the problem section, a missing break runs the next case's code and overwrites the result, with no error to point at it. End every case with break or return, and mark deliberate fallthrough with a // falls through comment. ESLint's no-fallthrough rule catches the accidental kind.
2. Mixing strings and numbers
Feeding "2" from a form field into a switch with case 2: never matches because of ===, so execution always lands in default. Convert first with switch (Number(input)), or use string labels such as case "2":.
3. Testing ranges with case
With switch (score) { case score >= 90: ... }, each case value is true or false, and that boolean is compared with === to a number, so it never matches. Use if...else for ranges.
Best practices
Best practices
- Always include default and state what happens to an unknown value.
- Inside a function, prefer return over break; it is shorter and removes the fallthrough risk.
- When a value only maps to a piece of text, reach for a lookup object instead.
Mini challenge
Mini challenge: order status handler
Write getOrderAction(), which takes an order status and returns, as text, the action shop staff should take. Use a switch.
- Trim and lower-case the status before comparing it
- "pending" → "Send payment reminder", "paid" → "Pack the items", "cancelled" → "Refund the customer"
- "shipped" and "out-for-delivery" share "Share tracking link" through grouped cases
- An unknown status hits default and returns "Unknown status: " plus the original value
function getOrderAction(status) {
const normalized = ""; // TODO: trim and lower-case status
switch (normalized) {
// TODO: pending, paid and cancelled each return their own action
// TODO: shipped and out-for-delivery share one return
// TODO: default returns "Unknown status: " + the original status
}
}
const samples = ["paid", " SHIPPED ", "out-for-delivery", "cancelled", "lost"];
// TODO: print each sample next to getOrderAction(sample)Expected: "paid" => Pack the items " SHIPPED " => Share tracking link "out-for-delivery" => Share tracking link "cancelled" => Refund the customer "lost" => Unknown status: lost
Show hint
If every case uses return, you never need break. For grouping, write case "shipped": with nothing under it, immediately followed by case "out-for-delivery":.
Show solution
function getOrderAction(status) {
const normalized = status.trim().toLowerCase();
switch (normalized) {
case "pending":
return "Send payment reminder";
case "paid":
return "Pack the items";
case "shipped":
case "out-for-delivery":
return "Share tracking link";
case "cancelled":
return "Refund the customer";
default:
return "Unknown status: " + status;
}
}
const samples = ["paid", " SHIPPED ", "out-for-delivery", "cancelled", "lost"];
for (const sample of samples) {
console.log(JSON.stringify(sample) + " => " + getOrderAction(sample));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- switch evaluates its expression once and checks cases top to bottom with ===, never converting types.
- From the matching case, execution runs downward until break or return (fallthrough).
- Stacked labels share code, and default is your policy for unknown values.
- Prefer if...else for ranges and a lookup object for simple value-to-value mappings.
MDN — JavaScript Guide — MDN Web Docs