switch expression
The value being compared, such as status, view or command.
switch compares one expression against multiple cases. It is useful when one value can have several known states.
const view = "settings";
switch (view) {
case "overview":
console.log("Show overview");
break;
case "settings":
console.log("Show settings");
break;
default:
console.log("Show fallback");
}
Control Flow
A switch statement evaluates one expression and compares it to case labels with strict comparison. When a case matches, JavaScript starts running from that point.
Most switch branches should end with break, return or throw. Without that, execution continues into the next case. That behavior is called fallthrough.
Use switch when it makes the value-to-behavior mapping easier to scan than a long else if chain. If every branch has a different condition shape, if/else is usually clearer.
The value being compared, such as status, view or command.
A possible matching value. Cases use strict comparison.
Stops execution from falling into the next case.
Fallback branch when no case matches.
Examples
const status = "published";
switch (status) {
case "draft":
label = "Continue editing";
break;
case "published":
label = "Visible";
break;
default:
label = "Unknown status";
}
switch (status) {
case "draft":
label = "Continue editing";
case "published":
label = "Visible";
}
// A draft status continues into the published case.
Rules that matter
Control flow decides which path code takes. Keep that path visible: name conditions, protect loop boundaries, avoid accidental fallthrough and use early exits only when they make the main path clearer.
The pattern is strongest when every case compares the same expression.
Use break, return or throw unless fallthrough is intentional and commented.
A fallback makes unexpected values visible.
Large branches belong in functions.
If every case only returns a value, an object or Map can be cleaner.
Normalize external strings before routing on them.
Production thinking
Many interfaces have states: loading, empty, ready, error. switch can make those state decisions easy to scan.
A switch often chooses status text. Always make fallback states understandable for users and assistive technology.
Production switches should handle unknown values. Silent missing cases become hard-to-debug UI states.
When switch controls rendered content, a missing default can leave important sections empty.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
Read each question out loud and answer it without looking at the examples. Control flow only clicks when you can trace the path in your own words.