|

JavaScript 12 🧬 switch statement

The switch statement is used to execute different blocks of code based on the value of an expression. It provides a more concise and readable way to handle multiple conditions compared to using multiple if-else statements.


A Quick Look at the Examples

// Basic switch
let fruit = "apple";
switch (fruit) {
  case "apple":
    console.log("It's an apple!");
    break;
  case "banana":
    console.log("It's a banana!");
    break;
  case "orange":
    console.log("It's an orange!");
    break;
  default:
    console.log("Unknown fruit.");
}
// Output: "It's an apple!"

// Fall-through example (no break statements)
let day = 2;
switch (day) {
  case 1:
    console.log("Monday");
  case 2:
    console.log("Tuesday");
  case 3:
    console.log("Wednesday");
  default:
    console.log("Weekend");
}
// Output: Tuesday, Wednesday, Weekend

// Grouping example (multiple cases sharing a block)
let number = 10;
switch (number) {
  case 1:
  case 2:
  case 3:
    console.log("Small number");
    break;
  case 4:
  case 5:
  case 6:
    console.log("Medium number");
    break;
  default:
    console.log("Large number");
}
// Output: "Large number"

a. Switch Statement Info

The switch statement is used to execute different blocks of code based on the value of an expression.

Syntax

switch (expression) {
  case value1:
    // Code to be executed if expression === value1
    break;
  case value2:
    // Code to be executed if expression === value2
    break;
  case value3:
    // Code to be executed if expression === value3
    break;
  default:
    // Code to be executed if none of the cases match
}

Key Components

ComponentDescription
ExpressionThe value the switch evaluates
Case LabelsPossible values to match against the expression
Break StatementTerminates the switch block, preventing fall-through
Default CaseRuns if no case matches (optional)

Important Rules

  1. Expression → The switch statement evaluates this expression once.
  2. Case Labels → Each case specifies a possible value for the expression.
  3. Comparison → Uses strict equality (===) — type matters!
  4. Break Statement → Used to terminate the switch block and prevent fall-through.
  5. Fall-through → If you omit break, execution continues into the next case, even if it doesn’t match.
  6. Default Case → Specifies a default block if none of the case labels match.

b. Switch Examples

Example 1: Basic Switch

let fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("It's an apple!");
    break;
  case "banana":
    console.log("It's a banana!");
    break;
  case "orange":
    console.log("It's an orange!");
    break;
  default:
    console.log("Unknown fruit.");
}

Output:

It's an apple!

How it works:

  1. fruit is "apple"
  2. Case "apple" matches → runs console.log("It's an apple!")
  3. break exits the switch

Example 2: Fall-Through (No Break)

let day = 2;

switch (day) {
  case 1:
    console.log("Monday");
  case 2:
    console.log("Tuesday");
  case 3:
    console.log("Wednesday");
  default:
    console.log("Weekend");
}

Output:

Tuesday
Wednesday
Weekend

How it works:

  1. day is 2
  2. Case 2 matches → runs console.log("Tuesday")
  3. No break → falls through to case 3 → runs console.log("Wednesday")
  4. No break → falls through to default → runs console.log("Weekend")
  5. Switch ends

⚠️ Warning: Fall-through is usually a bug, but it can be intentional in certain patterns.


Example 3: Grouping Cases

let number = 10;

switch (number) {
  case 1:
  case 2:
  case 3:
    console.log("Small number");
    break;
  case 4:
  case 5:
  case 6:
    console.log("Medium number");
    break;
  default:
    console.log("Large number");
}

Output:

Large number

How it works:

  1. number is 10
  2. No case matches (16 don’t match 10)
  3. default runs → console.log("Large number")

Grouping pattern: Multiple cases sharing the same code block (cases 1, 2, 3 all run the same code).


Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Switch Statement</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }
        h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
        h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
        .demo-box {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin: 15px 0;
        }
        pre {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            line-height: 1.8;
        }
        .keyword { color: #569cd6; }
        .string { color: #ce9178; }
        .number { color: #b5cea8; }
        .function { color: #dcdcaa; }
        .comment { color: #6a9955; }
        .boolean { color: #569cd6; }
        #output {
            background: #e9ecef;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            min-height: 40px;
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
            border-left: 4px solid #007bff;
            white-space: pre-wrap;
        }
        .input-group {
            margin: 10px 0;
        }
        .input-group label {
            display: inline-block;
            min-width: 120px;
            font-weight: bold;
        }
        .input-group input, .input-group select {
            padding: 8px 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 1em;
            width: 200px;
        }
        .input-group input:focus, .input-group select:focus {
            outline: none;
            border-color: #007bff;
        }
        .btn {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            margin: 5px;
            transition: all 0.3s;
        }
        .btn:hover {
            background: #0056b3;
            transform: translateY(-2px);
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        th { background: #007bff; color: white; }
        tr:nth-child(even) { background: #f8f9fa; }
    </style>
</head>
<body>

    <h1>Switch Statement</h1>

    <div class="demo-box">
        <h2>1. Basic Switch</h2>
        <pre>
<span class="keyword">let</span> fruit = <span class="string">"apple"</span>;

<span class="keyword">switch</span> (fruit) {
  <span class="keyword">case</span> <span class="string">"apple"</span>:
    console.log(<span class="string">"It's an apple!"</span>);
    <span class="keyword">break</span>;
  <span class="keyword">case</span> <span class="string">"banana"</span>:
    console.log(<span class="string">"It's a banana!"</span>);
    <span class="keyword">break</span>;
  <span class="keyword">default</span>:
    console.log(<span class="string">"Unknown fruit."</span>);
}
        </pre>
    </div>

    <div class="demo-box">
        <h2>2. Fall-Through (No break)</h2>
        <pre>
<span class="keyword">let</span> day = <span class="number">2</span>;

<span class="keyword">switch</span> (day) {
  <span class="keyword">case</span> <span class="number">1</span>:
    console.log(<span class="string">"Monday"</span>);
  <span class="keyword">case</span> <span class="number">2</span>:
    console.log(<span class="string">"Tuesday"</span>);
  <span class="keyword">case</span> <span class="number">3</span>:
    console.log(<span class="string">"Wednesday"</span>);
  <span class="keyword">default</span>:
    console.log(<span class="string">"Weekend"</span>);
}
        </pre>
        <p class="note">⚠️ Without <code>break</code>, execution falls through!</p>
    </div>

    <div class="demo-box">
        <h2>3. Grouping Cases</h2>
        <pre>
<span class="keyword">let</span> number = <span class="number">10</span>;

<span class="keyword">switch</span> (number) {
  <span class="keyword">case</span> <span class="number">1</span>:
  <span class="keyword">case</span> <span class="number">2</span>:
  <span class="keyword">case</span> <span class="number">3</span>:
    console.log(<span class="string">"Small number"</span>);
    <span class="keyword">break</span>;
  <span class="keyword">case</span> <span class="number">4</span>:
  <span class="keyword">case</span> <span class="number">5</span>:
  <span class="keyword">case</span> <span class="number">6</span>:
    console.log(<span class="string">"Medium number"</span>);
    <span class="keyword">break</span>;
  <span class="keyword">default</span>:
    console.log(<span class="string">"Large number"</span>);
}
        </pre>
    </div>

    <div class="demo-box">
        <h2>4. Interactive: Day of Week</h2>
        <div class="input-group">
            <label for="daySelect">Select a day:</label>
            <select id="daySelect">
                <option value="1">1 - Monday</option>
                <option value="2">2 - Tuesday</option>
                <option value="3">3 - Wednesday</option>
                <option value="4">4 - Thursday</option>
                <option value="5">5 - Friday</option>
                <option value="6">6 - Saturday</option>
                <option value="7">7 - Sunday</option>
            </select>
        </div>
        <button class="btn" onclick="checkDayNumber()">Check Day</button>
        <div id="dayNumberOutput"></div>
    </div>

    <div class="demo-box">
        <h2>5. Interactive: Grade with Switch</h2>
        <div class="input-group">
            <label for="gradeInput">Enter a grade:</label>
            <select id="gradeInput">
                <option value="A">A</option>
                <option value="B">B</option>
                <option value="C">C</option>
                <option value="D">D</option>
                <option value="F">F</option>
            </select>
        </div>
        <button class="btn" onclick="checkGrade()">Check Grade</button>
        <div id="gradeOutput"></div>
    </div>

    <div class="demo-box">
        <h2>6. Live Output — All Examples</h2>
        <div id="output">Loading...</div>
    </div>

    <script>
        // ============================================
        // Switch Statement — Live Demo
        // ============================================

        let results = [];

        // 1. Basic switch
        results.push('📌 Basic Switch:\n');
        const fruits = ["apple", "banana", "orange", "grape"];
        fruits.forEach(fruit => {
            let message;
            switch (fruit) {
                case "apple":
                    message = "It's an apple!";
                    break;
                case "banana":
                    message = "It's a banana!";
                    break;
                case "orange":
                    message = "It's an orange!";
                    break;
                default:
                    message = "Unknown fruit.";
            }
            results.push('  fruit = "' + fruit + '" → ' + message);
        });
        results.push('');

        // 2. Fall-through demonstration
        results.push('📌 Fall-Through (No break):\n');
        results.push('  switch (day = 2) { case 1: ... case 2: ... case 3: ... default: }');
        results.push('  → Falls through: Tuesday, Wednesday, Weekend');
        results.push('  ⚠️ Without break, execution continues to the next case!');
        results.push('');

        // 3. Grouping cases
        results.push('📌 Grouping Cases:\n');
        const testNumbers = [2, 5, 10];
        testNumbers.forEach(num => {
            let message;
            switch (num) {
                case 1:
                case 2:
                case 3:
                    message = "Small number";
                    break;
                case 4:
                case 5:
                case 6:
                    message = "Medium number";
                    break;
                default:
                    message = "Large number";
            }
            results.push('  number = ' + num + ' → ' + message);
        });
        results.push('');

        // 4. Switch with strings
        results.push('📌 Switch with Strings:\n');
        const commands = ["start", "stop", "pause", "unknown"];
        commands.forEach(cmd => {
            let action;
            switch (cmd) {
                case "start":
                    action = "▶️ Starting...";
                    break;
                case "stop":
                    action = "⏹️ Stopping...";
                    break;
                case "pause":
                    action = "⏸️ Pausing...";
                    break;
                default:
                    action = "❓ Unknown command";
            }
            results.push('  "' + cmd + '" → ' + action);
        });
        results.push('');

        // 5. Switch vs if...else comparison
        results.push('📌 Switch vs if...else:\n');
        results.push('  switch — best for EXACT value matches');
        results.push('  if...else — best for RANGE checks and complex conditions');
        results.push('');

        // 6. Strict equality reminder
        results.push('📌 Strict Equality (===) Reminder:\n');
        const testValue = "1";
        let strictResult;
        switch (testValue) {
            case 1:
                strictResult = "Matched number 1";
                break;
            case "1":
                strictResult = "Matched string '1'";
                break;
            default:
                strictResult = "No match";
        }
        results.push('  switch ("1") { case 1: ...; case "1": ... }');
        results.push('  → ' + strictResult + ' (strict equality matters!)');

        document.getElementById('output').textContent = results.join('\n');

        // ============================================
        // Interactive Functions
        // ============================================

        function checkDayNumber() {
            const day = Number(document.getElementById('daySelect').value);
            const output = document.getElementById('dayNumberOutput');
            let message;

            switch (day) {
                case 1:
                    message = "Monday — Start of the week 💼";
                    break;
                case 2:
                    message = "Tuesday — Keep going 💪";
                    break;
                case 3:
                    message = "Wednesday — Halfway there 🎯";
                    break;
                case 4:
                    message = "Thursday — Almost Friday 🚀";
                    break;
                case 5:
                    message = "Friday — Almost weekend! 🎉";
                    break;
                case 6:
                case 7:
                    message = "Weekend! Relax! 🌴";
                    break;
                default:
                    message = "Invalid day";
            }

            output.innerHTML = `<p><strong>Day ${day}</strong> → ${message}</p>`;
        }

        function checkGrade() {
            const grade = document.getElementById('gradeInput').value;
            const output = document.getElementById('gradeOutput');
            let message;

            switch (grade) {
                case "A":
                    message = "Excellent! 🌟";
                    break;
                case "B":
                    message = "Good job! 👍";
                    break;
                case "C":
                    message = "Average 📝";
                    break;
                case "D":
                    message = "Needs improvement 📚";
                    break;
                case "F":
                    message = "Failed — study harder! 💪";
                    break;
                default:
                    message = "Invalid grade";
            }

            output.innerHTML = `<p>Grade <strong>${grade}</strong> → ${message}</p>`;
        }

        // Run initial checks
        checkDayNumber();
        checkGrade();
    </script>

</body>
</html>

Quick Reference

Switch Syntax

switch (expression) {
    case value1:
        // Code
        break;
    case value2:
        // Code
        break;
    default:
        // Code if no match
}

Key Components

ComponentDescription
switch (expression)Evaluates the expression once
case value:Compares using strict equality (===)
break;Exits the switch (prevents fall-through)
default:Runs if no case matches (optional)

Fall-Through Behavior

ScenarioBehavior
With breakExits after matching case
Without breakContinues to next case(s)
Intentional fall-throughGroup cases for shared code

Switch vs if…else

Aspectswitchif...else
Best forExact value matchesRanges, complex conditions
ComparisonStrict equality (===)Any comparison
ReadabilityCleaner for many exact casesBetter for complex logic
Fall-throughPossible (watch out!)Not applicable
PerformanceCan be faster (jump table)Sequential checks

Best Practices

Do This:

// Always use break (unless intentional fall-through)
switch (value) {
    case "a":
        doSomething();
        break;
    case "b":
        doSomethingElse();
        break;
    default:
        handleDefault();
}

// Group cases that share the same code
switch (day) {
    case 6:
    case 7:
        console.log("Weekend!");
        break;
    default:
        console.log("Weekday");
}

// Include a default case
switch (fruit) {
    case "apple": /* ... */ break;
    default: console.log("Unknown");
}

// Use braces for case blocks with declarations
switch (value) {
    case 1: {
        const x = 10;
        console.log(x);
        break;
    }
}

Don’t Do This:

// Don't forget break (unless intentional)
switch (day) {
    case 1:
        console.log("Monday");
        // Missing break — falls through!
    case 2:
        console.log("Tuesday");
}

// Don't use switch for ranges
switch (score) {
    case score >= 90: // ❌ This doesn't work as expected!
        // Use if...else for ranges
}

// Don't forget strict equality
switch ("1") {
    case 1: // ❌ Won't match — "1" !== 1
        break;
}

// Don't declare variables without braces in cases
switch (value) {
    case 1:
        const x = 10; // ❌ SyntaxError in strict mode
        break;
}

Common Pitfalls

PitfallProblemSolution
Missing breakFall-throughAdd break
Using == logicSwitch uses ===Match types exactly
Variables in casesScope issuesWrap in { }
Range checksSwitch doesn’t support rangesUse if...else
Forgetting defaultNo fallback for unmatchedAdd default

When to Use Switch vs if…else

Use switch when…Use if...else when…
Comparing one value to many exact optionsChecking ranges (age > 18)
Values are simple (strings, numbers)Conditions are complex
You want cleaner, more readable codeYou need logical operators (&&, `
Fall-through is intentionalYou need early returns

Pro Tip: switch uses strict equality (===) — so "1" won’t match 1. Always add break unless you intentionally want fall-through. Use grouped cases (multiple case labels before one block) to share code. And remember: switch is best for exact value matches — for range checks like score >= 90, use if...else instead!


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!