JavaScript • Control Flow

Switch Statements — Use switch statements and understand fall-through

Master the elegant alternative to long if-else chains and learn how fall-through behavior works.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

When you write a program that needs to choose between many options — like responding to different key presses, handling menu selections, or grading an exam — you could stack up a long chain of if...else if...else statements. That works, but it quickly becomes hard to read. The switch statement was designed to solve exactly this problem: it gives programmers a cleaner, more organized way to handle multiple possible values of a single expression.

The switch statement didn't originate in JavaScript. Its roots go back decades in programming language history, and understanding that history helps you appreciate why it works the way it does today — including its sometimes-surprising fall-through behavior.

1960s • Early Multi-Way Branching

Languages like FORTRAN introduced computed GOTO statements and arithmetic IF statements to handle multiple branches, but these were error-prone and hard to follow.

1972 • C Introduces the Switch Statement

Dennis Ritchie created the C programming language, which included a switch statement with explicit fall-through behavior. This design choice was intentional — it allowed multiple cases to share code efficiently.

1995 • JavaScript Adopts the Switch

Brendan Eich created JavaScript and borrowed the switch syntax directly from C and Java, preserving the same fall-through behavior and structure that programmers already knew.

2015+ • Modern JavaScript and Beyond

ES6 and later versions of JavaScript kept the switch statement unchanged. Developers now also use object lookups and other patterns, but switch remains a fundamental control flow tool.

So here's the core question: when your code encounters a variable that could be one of many values, how do you handle each possibility in a way that's both readable and efficient? The switch statement is JavaScript's answer.

SECTION 2

Core Principles & Definitions

A switch statement evaluates an expression once and then compares its result against a series of case labels. When a match is found, the code inside that case runs. If no match is found, an optional default block runs instead. There are a few fundamental ideas you need to understand before writing your first switch statement.

1

The Switch Expression

The value inside switch(expression) is evaluated once. This result is then compared to each case value using strict equality (===), meaning both value and type must match.
2

Case Labels

Each case value: acts like an entry point. When the expression matches a case value, execution begins at that point and continues downward through subsequent cases unless stopped.
3

The Break Statement

The break keyword exits the switch block entirely. Without it, code execution "falls through" into the next case — which is sometimes intentional but often a bug.
4

The Default Case

The default: block is like the else in an if-else chain. It runs when no case matches. It's optional, but good practice to include one.
5

Fall-Through Behavior

When a matching case is found and there is no break, execution continues into the next case's code — regardless of whether that next case matches. This is called fall-through.
✦

KEY TAKEAWAY

Think of a switch statement like a vending machine. You press a button (the expression), and the machine checks each slot label (the cases) until it finds a match. Without break, the machine keeps dispensing items from every slot below the match — that's fall-through. The break statement is like the machine's mechanism that stops after dispensing just the one item you selected.

SECTION 3

Visual Explanation — Switch Statement Flow

The diagram below shows how JavaScript processes a switch statement from top to bottom. Notice how execution enters at the matching case and how break redirects program flow to exit the entire switch block. When break is absent, execution falls straight through to the next case's code.

Switch Statement Execution Flowswitch(expr)case "A": match?NoYes// run case A codecase "B": match?// run case B codebreak;case "C": match?// run case C codedefault: // fallback codeExit Switch Block1. Evaluate2. Compare3. Break exits4. Default runs if no match
The flowchart shows how a switch statement evaluates the expression, checks each case from top to bottom, and either executes code upon a match or skips to the next case. The green break path shows how execution exits the switch block. Without break, execution would continue into the next case below.

Notice how the flow only moves downward. JavaScript never goes back up to re-check a previous case. Once a match is found, all code below that point will execute unless a break statement tells JavaScript to jump out. This top-to-bottom behavior is exactly what makes fall-through possible — and sometimes dangerous if you forget your breaks.

SECTION 4

How Switch Statements Work — The Mechanics

Basic Syntax

Every switch statement follows the same basic structure. The keyword switch is followed by an expression in parentheses. Inside the curly braces, you write one or more case clauses, each followed by a colon and the code to execute. Here is the general template:

SWITCH SYNTAX TEMPLATE

switch(expression)casevalue1://codeforvalue1break;casevalue2://codeforvalue2break;default://codeifnomatchswitch (expression) { case value1: // code for value1 break; case value2: // code for value2 break; default: // code if no match }

expression — any JavaScript expression that produces a value. value1, value2 — the values to compare against using === (strict equality). break — exits the switch block after a match.

Strict Equality Comparison

A critical detail is that switch uses strict equality (===), not loose equality (==). This means that switch(1) will NOT match case "1": because the number 1 and the string "1" are different types. Always make sure your case values have the same data type as your switch expression.

Understanding Fall-Through in Detail

Fall-through happens when you omit the break statement from a case. Once JavaScript finds a matching case, it begins executing code and does not check the remaining case labels — it simply runs all code sequentially until it hits a break or reaches the end of the switch block. This is why fall-through can be both a powerful feature and a common source of bugs.

⚠

Common Mistake

Forgetting break is one of the most frequent bugs in JavaScript. If you write three cases without breaks and the first one matches, all three cases' code will run. Always include break unless you specifically intend fall-through behavior.

SECTION 5

Fall-Through — When and Why to Use It

While forgetting break is a common bug, there are legitimate situations where intentional fall-through makes your code cleaner. The most common use case is when multiple values should produce the same result. Instead of duplicating code across several cases, you can stack the case labels together and let them fall through to a single block of code.

Fall-Through: With Break vs. Without Break✓ WITH BREAK (Normal)case "Mon": log("Monday");break; ← exits herecase "Tue": log("Tuesday");break; ← exits herecase "Wed": log("Wednesday");break; ← exits hereOutput for "Mon":"Monday"Only ONE case runs ✓✗ WITHOUT BREAK (Fall-Through)case "Mon": log("Monday");falls!case "Tue": log("Tuesday");falls!case "Wed": log("Wednesday");falls!default: log("Unknown");Output for "Mon":"Monday""Tuesday""Wednesday""Unknown"ALL cases run ✗ (Bug!)
Left panel: each case ends with break, so only the matching case's code runs. Right panel: no breaks are present, so when "Mon" matches, JavaScript keeps running through all subsequent cases, outputting four lines instead of one.

Intentional Fall-Through: Grouping Cases

Here's a practical example where fall-through is actually helpful. Suppose you want to classify a day of the week as either a weekday or a weekend day. Instead of writing the same code twice, you can stack the cases:

INTENTIONAL FALL-THROUGH EXAMPLE

switch(day)case"Saturday":case"Sunday":console.log("Weekend!");break;case"Monday":case"Tuesday":case"Wednesday":case"Thursday":case"Friday":console.log("Weekday.");break;switch (day) { case "Saturday": case "Sunday": console.log("Weekend!"); break; case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": console.log("Weekday."); break; }

Cases "Saturday" and "Sunday" both fall through to the same console.log("Weekend!") statement. Similarly, all five weekday cases share one output. This is clean, readable, and completely intentional.

💡

Pro Tip

When you use intentional fall-through, add a comment like // fall through to signal to other developers (and your future self) that the missing break is deliberate, not an accident.

SECTION 6

Worked Example — Building a Grade Calculator

Let's build a switch statement that converts a letter grade into feedback. We'll walk through each step so you can see the thought process.

Letter Grade Feedback Generator

  1. 1

    Step 1 — Identify the Expression

    We have a variable called grade that holds a string like "A", "B", "C", "D", or "F". This will be our switch expression: switch (grade). Since the variable is a string, all our case values must also be strings.
    let grade = "B";
  2. 2

    Step 2 — Write Each Case with Break

    We write a case for each possible grade. Each case prints a message using console.log() and ends with break; to prevent fall-through. Here's the full structure:
    switch (grade) { case "A": console.log("Excellent work!"); break; case "B": console.log("Good job!"); break; case "C": console.log("You passed."); break; case "D": console.log("Needs improvement."); break; case "F": console.log("See your teacher."); break; default: console.log("Invalid grade."); }
  3. 3

    Step 3 — Trace Execution for grade = "B"

    JavaScript evaluates grade, which is "B". It compares "B" === "A" — no match. Then "B" === "B" — match! It runs console.log("Good job!") and hits break, which exits the switch block immediately.
    Output: "Good job!"
  4. 4

    Step 4 — Test the Default Case

    What if grade = "X"? JavaScript checks every case — "A", "B", "C", "D", "F" — none match. It reaches the default block and runs console.log("Invalid grade."). The default catches any unexpected input, making our code more robust.
    Output: "Invalid grade."
  5. 5

    Step 5 — Enhance with Fall-Through

    Suppose we want "A" and "B" to both say "Great work!" and "D" and "F" to both say "You need help." We can use intentional fall-through to group them: case "A": case "B": console.log("Great work!"); break;. This eliminates duplicate code and keeps things organized.
    Grouped cases share a single code block via intentional fall-through

SECTION 7

Switch vs. If-Else — When to Use Each

Both switch statements and if-else chains are tools for making decisions in your code. Choosing the right one depends on the situation. Here's a detailed comparison to help you decide.

FeatureSwitch StatementIf-Else Chain
Best forComparing one expression against many fixed valuesComplex conditions, ranges, or boolean logic
Comparison typeStrict equality (===) onlyAny comparison operator (<, >, ===, &&, ||, etc.)
ReadabilityCleaner with 4+ optionsCleaner with 1−3 conditions
Fall-throughSupported — can group casesNot applicable
Range checksNot directly supportedNatural fit (e.g., if score >= 90)
Common pitfallForgetting break (accidental fall-through)Deeply nested else-if can be hard to read

Comparison of switch statements and if-else chains

✦

KEY TAKEAWAY

Think of it this way: if you're checking which specific channel the TV is on (channel 3, 5, 7, 11…), a switch is perfect because you're comparing one value against exact matches. If you're checking whether the volume is too loud (above 80), too soft (below 20), or just right, you need if-else because those are range-based conditions that switch can't handle directly.

SECTION 8

Connection to Advanced Patterns

As you grow as a developer, you'll encounter more sophisticated patterns that build on the ideas behind switch statements. Understanding switch now prepares you for these advanced concepts.

ConceptWhat You Know Now (Switch)What Comes Next
Multi-way branchingswitch with case labels and breakObject lookup tables — using an object's keys as "cases" for dynamic dispatch
Pattern matchingMatching exact values with ===TC39 pattern matching proposal — matching by structure, type, and destructuring
State machinesSwitching on a state variableLibraries like XState use switch-like logic to manage complex UI states
ReducersHandling different cases with different codeReact/Redux reducers use switch statements to handle different action types

How switch concepts connect to advanced JavaScript patterns

In frameworks like React, the reducer pattern is essentially a switch statement inside a function. Each case corresponds to a different action that can change the application's state. If you master switch now, learning reducers later will feel natural. Also keep an eye on the pattern matching proposal — a potential future JavaScript feature that would make multi-way branching even more powerful.

ℹ

Object Lookup Alternative

Experienced developers sometimes replace switch statements with object lookups like const actions = { "A": "Excellent", "B": "Good" }; console.log(actions[grade]);. This pattern is more concise for simple value mapping, but switch remains better when each case requires different logic or multiple statements.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain what happens when JavaScript encounters a case label that matches the switch expression but the case does NOT have a break statement. Why is this called "fall-through"?
Show answer
When a matching case lacks a break statement, JavaScript does not stop executing after that case's code. Instead, it continues running the code for all subsequent cases below it — regardless of whether those case values match the expression. This is called "fall-through" because execution "falls" from one case into the next, like water flowing over steps in a staircase. The term emphasizes the downward, unstoppable flow of execution through the switch block until a break is encountered or the block ends.

Question 2: BASIC CALCULATION

What will the following code output? Trace through it step by step. let fruit = "banana"; switch (fruit) { case "apple": console.log("Red"); break; case "banana": console.log("Yellow"); break; case "grape": console.log("Purple"); break; default: console.log("Unknown color"); }
Show answer
The output is "Yellow". JavaScript evaluates fruit, which is "banana". It first checks "apple" === "banana" — no match. Then it checks "banana" === "banana" — match! It executes console.log("Yellow") and then hits break, which exits the switch. The "grape" and default cases are never reached.

Question 3: INTERMEDIATE

What will this code output, and why? let num = 2; switch (num) { case 1: console.log("One"); case 2: console.log("Two"); case 3: console.log("Three"); break; case 4: console.log("Four"); }
Show answer
The output is "Two" followed by "Three" (two lines). JavaScript matches case 2 and starts executing from there. It prints "Two", then falls through to case 3 (without checking whether 2 === 3) and prints "Three". Then it hits the break in case 3, which exits the switch. Case 4 is not reached. This demonstrates how fall-through continues until a break is encountered.

Question 4: APPLIED

Write a switch statement that takes a variable month (a number from 1 to 12) and uses intentional fall-through to set a variable season to "Winter", "Spring", "Summer", or "Fall". Months 12, 1, and 2 are Winter; 3, 4, 5 are Spring; 6, 7, 8 are Summer; 9, 10, 11 are Fall. Include a default case.
Show answer
Here is the solution: 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"; } This uses intentional fall-through to group three months per season. Cases 12, 1, and 2 all fall through to the "Winter" assignment. Each group ends with break to prevent further fall-through. The default handles invalid numbers gracefully.

Question 5: CRITICAL THINKING

Consider this code: let x = "5"; switch (x) { case 5: console.log("Number five"); break; case "5": console.log("String five"); break; } What will it output? Now imagine you change the first line to let x = 5;. What changes, and why? What does this reveal about switch compared to if-else with ==?
Show answer
With let x = "5", the output is "String five". The switch uses strict equality (===), so "5" === 5 is false (different types), but "5" === "5" is true. If you change x to the number 5, the output becomes "Number five" because now 5 === 5 is true and the first case matches. This reveals a key difference: an if-else chain using loose equality (==) would treat 5 and "5" as equal, matching either case. Switch's strict comparison makes it more predictable but demands that you pay close attention to data types. This is actually an advantage — it forces you to be explicit about what types you expect, reducing subtle bugs.

SUMMARY

Lesson Summary

Summary

A switch statement evaluates a single expression and compares it against multiple case labels using strict equality (===). When a match is found, JavaScript executes the code from that point forward. The break statement is essential — it tells JavaScript to exit the switch block after running the matched case's code. Without it, execution falls through into subsequent cases, running their code regardless of whether they match.

The default case acts as a safety net for unexpected values, much like the final else in an if-else chain. Intentional fall-through is a legitimate technique for grouping multiple case values that share the same code. Switch statements are ideal when comparing one expression against many discrete values, while if-else chains are better for complex conditions, ranges, and boolean logic. Mastering switch prepares you for advanced patterns like reducers and state machines used in modern JavaScript frameworks.

Varsity Tutors • JavaScript • Switch Statements — Use switch statements and understand fall-through