Computer Programming 1 (JavaScript) • Conditionals, Loops & Common Patterns

Switch Statements — I can use a switch statement for multi-case branching when it improves clarity at my level.

Replace long chains of if-else with a cleaner, more readable branching structure.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

Early programming languages forced developers to write long sequences of conditional checks that quickly became hard to read. As programs grew more complex in the 1960s, language designers realized they needed a cleaner way to handle situations where a single value could match one of many possible options. The switch statement was born from that need—a structured way to route program execution down one of several paths based on the value of a single expression.

1960 • ALGOL 60 and Computed Jumps

ALGOL 60 introduced early multi-way branching with computed go-to statements, letting a single variable control which part of the code ran next.

1972 • C Language Formalizes switch

Dennis Ritchie's C language introduced the switch keyword with case labels and break statements, establishing the syntax pattern still used in many languages today.

1995 • JavaScript Inherits the Pattern

Brendan Eich created JavaScript in just 10 days, borrowing C-style syntax—including the switch statement—to make the language feel familiar to existing developers.

2015+ • Modern Alternatives Emerge

ES6 and later brought objects as lookup tables and pattern matching proposals, but the switch statement remains a go-to tool for clear multi-case branching in JavaScript.

The central question behind the switch statement is simple: when you have a single value that might match many discrete options, what's the clearest way to express that choice? Understanding when to reach for a switch—and when to stick with if-else—is a key skill in writing readable code.

SECTION 2

Core Principles & Definitions

A switch statement evaluates a single expression and then compares its result against a series of case labels. When JavaScript finds a match, it executes the code in that case block. This design is built around a few foundational ideas you need to know before writing your first switch.

1

Expression Evaluation

The value inside switch(expr) is evaluated once, and that result is compared to each case. It can be a variable, a function call, or any valid expression.
2

Strict Equality (===)

JavaScript uses strict equality to compare the expression to each case. This means both the value and the type must match—no automatic type conversion happens.
3

Fall-Through Behavior

Without a break statement, execution falls through from one case into the next. This is intentional by design but is a common source of bugs for beginners.
4

The default Case

The default block runs when none of the case labels match the expression. Think of it like the final else in an if-else chain.
5

Readability Over Cleverness

Use a switch when you have three or more discrete values to check against the same variable. If your conditions involve ranges or complex logic, if-else is usually clearer.
✦

KEY TAKEAWAY

Think of a switch statement like a vending machine. You insert a coin (the expression), and the machine checks each button label (case) one by one. When it finds the button you pressed, it drops that specific snack (executes that case's code). If no button matches, the machine returns your coin (runs the default case). A break is like a stopper that prevents the machine from accidentally dispensing every snack below the one you chose.

SECTION 3

Visual Explanation — How a Switch Executes

switch (day)day === "Mon" ?YESrun Mon codeNOday === "Tue" ?YESrun Tue codeNOday === "Wed" ?YESrun Wed codeNO⋯ more cases ⋯default: fallback codeENDEvaluate once
The flowchart shows how a switch evaluates its expression once at the top, then checks each case using strict equality (===). A YES match branches right to execute that case's code; a NO continues downward to the next case. If nothing matches, the default block at the bottom runs.

In the diagram above, notice that the expression at the top is evaluated just once. This is one of the key differences from an if-else chain, where you might accidentally evaluate a function call multiple times. Each diamond-shaped check uses strict equality (===), meaning the type and value must both match. The green "YES" arrows show execution branching to the right when a match is found, and the red "NO" labels show how control falls to the next case. The default block sits at the bottom as a safety net, catching any value you didn't anticipate.

SECTION 4

How Switch Statements Work — The Syntax Deep Dive

Now that you understand the concept, let's break down the exact syntax. A switch statement in JavaScript has a specific structure, and every keyword plays an important role. Understanding each piece will help you avoid the most common mistakes.

The Anatomy of a Switch Statement

BASIC SWITCH SYNTAX

switch(expression)casevalue1://codeblockbreak;casevalue2://codeblockbreak;default://fallbackcodeswitch (expression) { case value1: // code block break; case value2: // code block break; default: // fallback code }

expression — the value being tested (evaluated once). case value — a possible match checked with ===. break — exits the switch block to prevent fall-through. default — runs if no case matches (optional but recommended).

Fall-Through: Feature or Bug?

One of the trickiest parts of switch statements is fall-through. When JavaScript matches a case and there is no break, execution continues into the next case's code regardless of whether that case matches. This can actually be useful when multiple values should produce the same result.

INTENTIONAL FALL-THROUGH (GROUPING CASES)

case"Mon":case"Tue":case"Wed":case"Thu":case"Fri":console.log("Weekday");break;case"Sat":case"Sun":console.log("Weekend");break;case "Mon": case "Tue": case "Wed": case "Thu": case "Fri": console.log("Weekday"); break; case "Sat": case "Sun": console.log("Weekend"); break;

Cases without code or a break statement fall through to the next case. Here, all five weekday cases share one code block, and both weekend cases share another.

⚠

Watch Out!

Forgetting break is the number-one switch statement bug. If you intend for each case to run independently, always include break (or return if inside a function). When you deliberately omit break for fall-through, add a comment like // falls through to signal your intent to anyone reading the code.

SECTION 5

Common Switch Patterns & When to Use Them

Not every branching problem calls for a switch. The key is knowing which situations benefit from the switch statement's structure and which are better served by if-else or other patterns. Below is a visual comparison that shows the same logic written both ways, so you can see when switch improves clarity.

if-else chainswitch statementif (grade === "A") { msg = "Excellent";}else if (grade === "B") { msg = "Good job";}else if (grade === "C") { msg = "Keep trying";} else { msg = "Invalid"; }switch (grade) {case "A": msg = "Excellent"; break;case "B": msg = "Good job"; break;case "C": msg = "Keep trying"; break;default: msg = "Invalid";Repeated "grade ===" is noisyEach case is visually distinct & scannable✅ Use switch when:• Comparing ONE expression against 3+ discrete values• Each value maps to a distinct action• You want code that's easy to scan at a glance❌ Stick with if-else when:• Conditions involve ranges, inequalities, or complex logic
Side-by-side comparison: the if-else chain on the left repeats grade === in every condition, adding visual noise. The switch version on the right cleanly separates each case, making it easier to scan and maintain.

The comparison highlights a simple rule of thumb: when you find yourself writing if (x === a) ... else if (x === b) ... else if (x === c), that pattern is a strong candidate for a switch. Each case label clearly states what value it handles, and the consistent break at the end of each block creates a visual rhythm that's easy to follow. However, if your conditions involve ranges (like score >= 90) or compound conditions (like age > 16 && hasLicense), stick with if-else because switch only compares for exact matches.

SECTION 6

Worked Example — Building a Day-of-Week Planner

Let's walk through a complete example step by step. Imagine you're building a simple web app that displays a different activity suggestion based on the day of the week. We'll start from the problem description and arrive at a working switch statement.

Activity Planner with Switch

  1. 1

    Step 1 — Identify the Branching Variable

    We need to determine which day of the week it is. JavaScript's new Date().getDay() returns a number from 0 (Sunday) to 6 (Saturday). This single numeric value will be our switch expression.
    const dayNum = new Date().getDay(); → returns 0–6
  2. 2

    Step 2 — Set Up the Switch Structure

    We write the switch keyword followed by the expression in parentheses, then open a block with curly braces. Each possible day number gets its own case label.
    switch (dayNum) { ... }
  3. 3

    Step 3 — Write Each Case with Break

    For each day, we assign a message to a variable called activity. Every case ends with break; to prevent fall-through. We group Saturday (6) and Sunday (0) to share a "Relax" message using intentional fall-through.
    case 0: case 6: activity = "Relax & recharge"; break;
  4. 4

    Step 4 — Add the Default Case

    Even though getDay() always returns 0–6, a default case is good defensive programming. If the value were somehow unexpected, the code wouldn't silently fail.
    default: activity = "Check your calendar";
  5. 5

    Step 5 — Complete Code

    Here is the full working solution: const dayNum = new Date().getDay(); let activity; switch (dayNum) { case 1: activity = "Study JavaScript"; break; case 2: activity = "Practice coding problems"; break; case 3: activity = "Build a project"; break; case 4: activity = "Review and debug"; break; case 5: activity = "Pair programming"; break; case 0: case 6: activity = "Relax & recharge"; break; default: activity = "Check your calendar"; } console.log(activity);
    On a Wednesday (dayNum = 3), the output is: "Build a project"

SECTION 7

Switch vs. If-Else — Strengths & Limitations

No tool is perfect for every job. Understanding the strengths and limitations of switch statements compared to if-else chains helps you make better decisions about which to use in your own code.

Featureswitch Statementif-else Chain
Best forComparing one expression to many discrete valuesRanges, inequalities, complex boolean logic
Comparison typeStrict equality (===) onlyAny boolean expression
ReadabilityExcellent when 3+ cases match one variableBetter for 1–2 conditions or mixed logic
Fall-throughSupported — useful for grouping cases, but risky if you forget breakNot applicable — each branch is independent
Expression evaluationEvaluated once at the topCondition re-evaluated at each else-if
Common pitfallMissing break causes unintended fall-throughLong chains become hard to read

Comparison of switch statements and if-else chains in JavaScript

💡

WHEN TO CHOOSE WHICH

Think of it like choosing between a labeled filing cabinet and a stack of sticky notes. When you have many items to sort into clear categories (like days, menu options, or user roles), the filing cabinet (switch) keeps everything organized. But when your sorting rules are fuzzy—like "put anything heavier than 10 lbs on the bottom shelf"—sticky-note logic (if-else) gives you the flexibility you need.

SECTION 8

Connection to Advanced Patterns

The switch statement is your first encounter with a broader programming concept called pattern matching—the idea that code should clearly express "when the data looks like this, do that." As you advance, you'll encounter more powerful variations of this idea.

ConceptWhat You Know NowWhat's Coming Next
Multi-way branchingswitch with case/breakObject lookup tables — mapping keys to values without any branching
Fall-through groupingStacking case labels to share codeArray .includes() checks to test membership
Pattern matchingMatching exact values with ===TC39 pattern matching proposal (Stage 2) — matching by structure, type, and value
State machinesUsing switch to handle different statesLibraries like XState for complex state management in apps

How switch concepts connect to more advanced patterns

One common pattern you'll see in intermediate courses is using an object lookup table as a cleaner alternative to switch when each case simply maps a key to a value. For example, const messages = { A: "Excellent", B: "Good", C: "Keep trying" }; lets you write messages[grade] instead of a whole switch block. But switch remains the better choice when each case involves multiple statements, side effects, or fall-through logic. For now, master the switch—it builds the mental model you'll need for every advanced pattern that comes later.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why JavaScript uses strict equality (===) instead of loose equality (==) when comparing the switch expression to each case value. What kind of bug could loose equality introduce?
Show answer
JavaScript uses strict equality (===) in switch statements to avoid unexpected type coercion. With loose equality (==), the number 0 would match the string "0", and the boolean false could match 0 or an empty string. This means a case might accidentally trigger for a value of a completely different type, producing silent bugs that are hard to track down. Strict equality ensures both the value and the type must match, making the switch statement's behavior predictable.

Question 2: BASIC CALCULATION

Write a switch statement that takes a variable month (a number 1–12) and sets a variable season to "Winter", "Spring", "Summer", or "Fall". Group the months using fall-through: Winter = 12, 1, 2; Spring = 3, 4, 5; Summer = 6, 7, 8; Fall = 9, 10, 11.
Show answer
Here is the correct solution using intentional fall-through: let season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Fall"; break; default: season = "Invalid month"; } Notice how cases 12, 1, and 2 are stacked without break statements so they all fall through to the same code block. The break after setting season = "Winter" prevents execution from continuing into the Spring cases. A default case handles any unexpected input.

Question 3: INTERMEDIATE

The following code has a bug. The developer expects it to log only the matching fruit's price, but it logs multiple prices. Find and fix the bug. let fruit = "banana"; switch (fruit) { case "apple": console.log("$1.20"); case "banana": console.log("$0.50"); case "cherry": console.log("$3.00"); default: console.log("Fruit not found"); }
Show answer
The bug is missing break; statements after each case. When fruit is "banana", JavaScript matches case "banana", logs "$0.50", then falls through to case "cherry" (logging "$3.00") and then through to default (logging "Fruit not found"). The fix is to add break; after each console.log. The corrected code: switch (fruit) { case "apple": console.log("$1.20"); break; case "banana": console.log("$0.50"); break; case "cherry": console.log("$3.00"); break; default: console.log("Fruit not found"); } Now only "$0.50" is logged when fruit is "banana".

Question 4: APPLIED

You're building a simple calculator function that takes two numbers and an operator string ("+", "-", "×", "÷"). Write a function calculate(a, op, b) using a switch statement on op that returns the correct result. Handle division by zero by returning the string "Error: division by zero". Include a default case for unsupported operators.
Show answer
function calculate(a, op, b) { switch (op) { case "+": return a + b; case "-": return a - b; case "×": return a * b; case "÷": if (b === 0) return "Error: division by zero"; return a / b; default: return "Unsupported operator"; } } Note that using return inside a function automatically exits the switch, so you don't need break statements. The division case includes an if-check inside it for the division-by-zero edge case—this is perfectly fine because switch cases can contain any valid JavaScript, including additional conditionals. Calling calculate(10, "÷", 0) returns "Error: division by zero", and calculate(3, "+", 7) returns 10.

Question 5: CRITICAL THINKING

A classmate argues: "You should always use switch instead of if-else because it looks cleaner." Write a short paragraph explaining when this claim is correct, when it's wrong, and provide one specific example where an if-else chain is clearly the better choice. Then rewrite that example as a switch and explain why it's worse.
Show answer
The claim is correct when you're comparing one expression against three or more specific, discrete values—like checking a user's role ("admin", "editor", "viewer") or a menu choice (1, 2, 3, 4). In these cases, switch eliminates the repetitive variable === noise and makes each option easy to scan. However, the claim is wrong when conditions involve ranges or inequalities. Consider assigning letter grades from a numeric score: // Clear with if-else: if (score >= 90) grade = "A"; else if (score >= 80) grade = "B"; else if (score >= 70) grade = "C"; else grade = "F"; A switch version would require listing every possible integer (case 100: case 99: case 98: ... case 90:) or using the awkward switch(true) hack, both of which are far less readable. The key principle is to choose the tool that makes your intent most obvious to the next person reading your code—including your future self.

SUMMARY

Lesson Summary

Summary

A switch statement evaluates a single expression once and compares the result to a series of case labels using strict equality (===). When a match is found, the corresponding code block executes. Every independent case should end with a break statement to prevent unintended fall-through, though fall-through can be used intentionally to group cases that share the same logic. A default case acts as a safety net for unexpected values.

Choose a switch over an if-else chain when you're comparing one variable against three or more discrete values and each value maps to a distinct action. Stick with if-else when your conditions involve ranges, inequalities, or compound boolean expressions. As you grow as a programmer, you'll connect the switch pattern to more advanced concepts like object lookup tables and pattern matching, but the core principle stays the same: write the code that makes your intent clearest.

Varsity Tutors • Computer Programming 1 (JavaScript) • Switch Statements