Tutorials JavaScript Switch Statement
Ch 17 / 78
Chapter 17 Beginner 6 min read JavaScript

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.

What you'll learn
switch syntax — expression, case, break, default
How strict equality (===) is used for matching
The break keyword and what happens without it
Intentional fall-through to group cases
The default case — switch's else equivalent
switch vs if/else — when to use each

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.

switch
Evaluates one expression and routes execution to the matching case.
case
Each label is a candidate value — matched with strict ===.
break
Exits the switch block. Without it, execution falls into the next case.
default
Fallback block — runs when no case matches, like else.
fall-through
Intentionally omit break to share code across multiple cases.
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.

Anatomy of a Switch Statement
switch (expr) The keyword and expression to evaluate. The result is compared against each case.
case value: A candidate label. If expr === value, execution jumps here and runs until break or end of switch.
break; Exits the switch block. Without break, execution falls through into the next case automatically.
default: Optional catch-all block — runs when no case matches. Equivalent to the else in if/else.
JavaScript — Basic switch
// ── 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 💼"
Best Practice
Always include a 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 (x)
Matches with strict ===
x = 1, case 1 match ✓
x = "1", case 1 no match
x = true, case 1 no match
x = "hi", case "hi" match ✓
x = null, case null match ✓
break
Exits after matched case runs
case match + break exits ✓
case match, no break falls through ⚠
no match + default default runs ✓
no match, no default nothing runs
return inside case exits fn ✓
JavaScript — Strict Equality in switch
// ── 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.

break
Stop & Exit
Immediately exits the switch block. Code after the switch continues normally.
break;
return
Exit Function
Inside a function, return exits both the switch and the function — no break needed.
return value;
no break
Fall-Through
Omitting break causes execution to continue into the next case. Usually a bug, sometimes intentional.
case "a": // no break
default
No-Match Fallback
Runs when no case matches. Can appear anywhere — usually placed last by convention.
default: ...
JavaScript — break vs Fall-Through
// ── 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" ← CORRECT
Common Mistake
Forgetting break 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.

JavaScript — Intentional Fall-Through (Grouping Cases)
// ── 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";
}
}
Pro Tip
You can pass 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.

✗ Long if/else chain
function getDiscount(tier) {
  if (tier === "gold")
    return 0.20;
  else if (tier === "silver")
    return 0.10;
  else if (tier === "bronze")
    return 0.05;
  else return 0;
}
✓ Clean switch + return
function getDiscount(tier) {
  switch (tier) {
    case "gold": return 0.20;
    case "silver": return 0.10;
    case "bronze": return 0.05;
    default: return 0;
  }
}
JavaScript — switch with return (no break needed)
// ── 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
Rule of Thumb
Use 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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These switch patterns appear constantly in real JavaScript projects. Master them to write clean, predictable, and expressive multi-branch logic.

JavaScript — switch Recipes
// ── 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";
}
}
⚡
Free Resource
Download our JavaScript Cheat Sheet
All conditionals, control flow patterns & decision trees — one printable page.
Get Sheet
Quick Check
What equality operator does switch use for case matching?
Quick Check
What happens if you omit break in a matched switch case?
Quick Check
Which output does switch("1") { case 1: ... } produce?
Chapter Summary
  • The switch statement evaluates an expression once and routes execution to the first matching case label using strict equality (===).
  • break exits the switch after a matched case. Without it, execution falls through into the next case — a common bug. Always add break unless fall-through is intentional.
  • The default case acts like else — 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 return instead of break — it exits both the switch and the function, keeping code cleaner.
  • Use switch for 6+ branches on a single variable with fixed discrete values. Use if/else for 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel