Switch Statement
The Switch Statement is a clean, readable alternative to long
else if chains when you need to compare a
single value against many fixed cases. It uses
=== strict equality for matching and lets you
group cases, fall through intentionally, and define a
default fallback — making branching logic
easier to scan and maintain.
Switch Statement Overview
The switch statement evaluates an
expression once and then compares the result against a series of
case labels using strict equality
(===). When a match is found, the associated
block runs until a break is hit — or the switch ends.
| Keyword | Purpose | When to Use |
|---|---|---|
| switch | Evaluate expression once, route to matching case | 6+ branches comparing a single variable |
| case | Label a candidate value for strict equality match | Every expected value in the switch |
| break | Exit the switch after a matched case | After every case (unless intentional fall-through) |
| default | Catch-all when no case matches | Always — handle unexpected values gracefully |
| fall-through | Omit break to continue into next case | Grouping cases that share the same logic |
Basic switch Syntax
A switch block starts with an
expression in parentheses. JavaScript evaluates it once and walks the
case labels top-to-bottom until it finds a strict
match. If none match, it runs the optional
default block.
// ── Basic Switch Statement ────────────────────────────────────
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week 💼");
break;
case "Wednesday":
console.log("Midweek — keep going 💪");
break;
case "Friday":
console.log("Last day — almost weekend! 🎉");
break;
default:
console.log("Just another day 📅");
}
// Output: "Start of the work week 💼"default case. Even if you're confident about
all possible values, a default acts as a safety net for unexpected inputs — especially
when data comes from user input or an external API. Think of it as the
else you always write.
switch Uses Strict Equality (===)
Unlike loose equality (==),
switch compares with
strict equality (===). This means both the
value and the type must match. A number
1 will NOT match a string
"1".
// ── switch uses === not == ────────────────────────────────────
switch (1) {
case 1: console.log("number 1"); break; // ✓ matches
case "1": console.log("string 1"); break; // ✗ different type
case true: console.log("boolean"); break; // ✗ different type
}
// Output: "number 1"
// ── Be careful with loose types ───────────────────────────────
const input = "2"; // user input is always a string
switch (input) {
case 2: console.log("number two"); break; // ✗ "2" !== 2
case "2": console.log("string two"); break; // ✓ matches
}
// ── Always convert types first if needed ─────────────────────
const num = Number(input);
switch (num) {
case 1: console.log("one"); break;
case 2: console.log("two"); break; // ✓ now matches
default: console.log("other");
}The break Keyword
After a case block executes, JavaScript does not
automatically stop. Without break, execution
falls through into the next case — even if that case's label doesn't
match. This is a common source of bugs for beginners. Always add
break unless you intentionally want fall-through.
return exits both the switch and the
function — no break needed.// ── Without break — accidental fall-through (BUG) ────────────
const x = 1;
switch (x) {
case 1: console.log("one"); // runs ✓
case 2: console.log("two"); // also runs ⚠ (fall-through!)
case 3: console.log("three"); // also runs ⚠
}
// Output: "one" "two" "three" ← BAD
// ── With break — correct behaviour ───────────────────────────
switch (x) {
case 1: console.log("one"); break; // runs, then exits ✓
case 2: console.log("two"); break; // skipped
case 3: console.log("three"); break; // skipped
}
// Output: "one" ← CORRECTbreak is one of the most frequent JavaScript bugs. If you copy a
case block and forget to add break, all subsequent cases will run silently.
Linters like ESLint can catch this with the
no-fallthrough rule — enable it in your project.
Intentional Fall-Through
Fall-through can be intentional and useful when multiple
case values should trigger the same block of code. Stack the cases
one after another with no body between them — only the last one in the group needs a
break.
// ── Weekend check — Saturday & Sunday share same logic ────────
const day = "Saturday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Weekday — work time 💼");
break;
case "Saturday":
case "Sunday": // intentional fall-through
console.log("Weekend! Rest up 🌴");
break;
default:
console.log("Unknown day");
}
// Output: "Weekend! Rest up 🌴"
// ── HTTP status grouping ──────────────────────────────────────
function getStatusCategory(code) {
switch (true) {
case (code >= 200 && code < 300): return "Success ✅";
case (code >= 300 && code < 400): return "Redirect 🔀";
case (code >= 400 && code < 500): return "Client Error ❌";
case (code >= 500): return "Server Error 💥";
default: return "Unknown";
}
}switch (true) and use boolean expressions in each case label.
This is a handy trick for range checks that would otherwise require a chain of
else if statements. Use it sparingly — it trades readability for conciseness.
switch Inside Functions
When a switch is inside a function,
you can use return instead of
break. Since return exits the entire
function, you never need a separate break — making the code
cleaner and less error-prone.
if (tier === "gold")
return 0.20;
else if (tier === "silver")
return 0.10;
else if (tier === "bronze")
return 0.05;
else return 0;
}
switch (tier) {
case "gold": return 0.20;
case "silver": return 0.10;
case "bronze": return 0.05;
default: return 0;
}
}
// ── Discount calculator ───────────────────────────────────────
function getDiscount(tier) {
switch (tier) {
case "gold": return 0.20; // 20% off
case "silver": return 0.10; // 10% off
case "bronze": return 0.05; // 5% off
default: return 0; // no discount
}
}
console.log(getDiscount("gold")); // 0.2
console.log(getDiscount("bronze")); // 0.05
console.log(getDiscount("vip")); // 0 (default)
// ── HTTP message lookup ───────────────────────────────────────
function httpMessage(code) {
switch (code) {
case 200: return "OK ✅";
case 201: return "Created ✨";
case 400: return "Bad Request ❌";
case 401: return "Unauthorized 🔒";
case 404: return "Not Found 🔍";
case 500: return "Server Error 💥";
default: return "Unknown Status";
}
}
console.log(httpMessage(404)); // "Not Found 🔍"
console.log(httpMessage(200)); // "OK ✅"switch vs if / else — When to Use Each
Both switch and
if/else can handle multiple branches, but they
excel in different situations. Knowing when to choose each makes your code
more readable and maintainable.
| Scenario | Use switch | Use if / else |
|---|---|---|
| Single variable, many exact values | ✓ Better | Works but verbose |
| Range checks (x > 10 && x < 20) | Not ideal | ✓ Better |
| Complex boolean expressions | Not possible | ✓ Better |
| Grouping multiple values → same code | ✓ Fall-through | Use || operator |
| 2–3 branches only | Overkill | ✓ Simpler |
| 6+ branches on one variable | ✓ Cleaner | Gets messy |
switch when you're comparing a single expression against many
fixed, discrete values (like day names, HTTP codes, user roles). Use
if/else for ranges, complex conditions, or fewer than 4 branches.
Try It — Live Editor
Experiment with the JavaScript Switch Statement below. Change values, test different cases, and observe how fall-through and default work — all without leaving this page.
Common Patterns & Recipes
These switch patterns appear constantly in real JavaScript projects. Master them to write clean, predictable, and expressive multi-branch logic.
// ── Role-based access control ─────────────────────────────────
function getPermissions(role) {
switch (role) {
case "admin": return ["read", "write", "delete"];
case "editor": return ["read", "write"];
case "viewer": return ["read"];
default: return [];
}
}
// ── Redux-style reducer ───────────────────────────────────────
function counterReducer(state = 0, action) {
switch (action.type) {
case "INCREMENT": return state + 1;
case "DECREMENT": return state - 1;
case "RESET": return 0;
default: return state;
}
}
// ── Theme colour mapping ──────────────────────────────────────
function getBadgeColor(status) {
switch (status) {
case "active": return "#22c55e";
case "pending": return "#f97316";
case "inactive": return "#6b7280";
case "error": return "#ef4444";
default: return "#94a3b8";
}
}
// ── Month name lookup ─────────────────────────────────────────
function getMonthName(n) {
switch (n) {
case 1: return "January"; case 7: return "July";
case 2: return "February"; case 8: return "August";
case 3: return "March"; case 9: return "September";
case 4: return "April"; case 10: return "October";
case 5: return "May"; case 11: return "November";
case 6: return "June"; case 12: return "December";
default: return "Invalid month";
}
}switch use for case matching?break in a matched switch case?switch("1") { case 1: ... } produce?- The
switchstatement evaluates an expression once and routes execution to the first matchingcaselabel using strict equality (===). breakexits the switch after a matched case. Without it, execution falls through into the next case — a common bug. Always addbreakunless fall-through is intentional.- The
defaultcase acts likeelse— it runs when no case matches. Always include it to handle unexpected values gracefully. - Intentional fall-through (stacking empty cases) lets multiple values share a single code block without repetition.
- Inside a function, use
returninstead ofbreak— it exits both the switch and the function, keeping code cleaner. - Use
switchfor 6+ branches on a single variable with fixed discrete values. Useif/elsefor ranges, complex boolean expressions, or fewer than 4 branches. - Always convert types before switching when input may come from
user input (strings) but you want to match numbers —
Number(input)first.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.