Learn the JavaScript switch statement with syntax, fall-through behavior, grouped cases, default clause, real-world examples, common mistakes, and interview Q&A for beginners.
The switch statement is a clean, readable way to execute different code blocks based on the value of a single expression. When you find yourself writing a long chain of if-else if-else if, a switch is often the better choice.
Simple definition: "Check this value. If it matches CASE 1, do this. If it matches CASE 2, do that. Otherwise do the DEFAULT."
📝 Syntax
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
case value3:
// code for value3
break;
default:
// code when nothing matches
}
How it works:
expression is evaluated once- Compared against each
case using strict equality (===) - First matching case's code runs
break stops execution and exits the switch- If no case matches,
default runs (if present)
💡 Real World Analogy
Analogy: A vending machine! You press a number:
- Press 1 → Cola
- Press 2 → Water
- Press 3 → Juice
- Press anything else → "Invalid choice"
The machine checks your input against each option and delivers the matching item. That's a switch statement!
✅ Basic Examples
Example 1: Day of the Week
let day = 3;
switch (day) {
case 1: console.log("Monday"); break;
case 2: console.log("Tuesday"); break;
case 3: console.log("Wednesday"); break;
case 4: console.log("Thursday"); break;
case 5: console.log("Friday"); break;
case 6: console.log("Saturday"); break;
case 7: console.log("Sunday"); break;
default: console.log("Invalid day number");
}
Example 2: Fruit Color Identifier
let fruit = "mango";
switch (fruit) {
case "apple":
console.log("Apple is red or green 🍎");
break;
case "banana":
console.log("Banana is yellow 🍌");
break;
case "mango":
console.log("Mango is yellow-orange 🥭");
break;
case "grapes":
console.log("Grapes are purple 🍇");
break;
default:
console.log("Unknown fruit");
}
Example 3: Simple Calculator
let a = 15, b = 4;
let operator = "%";
switch (operator) {
case "+":
console.log(`${a} + ${b} = ${a + b}`);
break;
case "-":
console.log(`${a} - ${b} = ${a - b}`);
break;
case "*":
console.log(`${a} * ${b} = ${a * b}`);
break;
case "/":
console.log(b !== 0 ? `${a} / ${b} = ${a / b}` : "Cannot divide by zero!");
break;
case "%":
console.log(`${a} % ${b} = ${a % b}`);
break;
default:
console.log("Unknown operator:", operator);
}
⚠️ Fall-Through Behavior — CRITICAL to Understand!
Without break, execution falls through to the next case!
Without Break (Fall-Through Bug)
let num = 2;
switch (num) {
case 1:
console.log("One");
case 2:
console.log("Two"); // ← matches here
case 3:
console.log("Three"); // ← ALSO runs (no break above!)
default:
console.log("Default"); // ← ALSO runs!
}
All cases after the match run because there are no break statements!
With Break (Correct Behavior)
let num = 2;
switch (num) {
case 1:
console.log("One");
break;
case 2:
console.log("Two"); // ← matches and runs
break; // ← stops here
case 3:
console.log("Three"); // ← skipped
break;
default:
console.log("Default"); // ← skipped
}
🔗 Intentional Fall-Through — Grouping Cases
Sometimes fall-through is intentional — when multiple values should produce the same result:
let day = "Saturday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Weekday — time to work! 💼");
break;
case "Saturday":
case "Sunday":
console.log("Weekend — time to relax! 🎉");
break;
default:
console.log("Invalid day");
}
Weekend — time to relax! 🎉
Seasons from Month Number
let month = 7;
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 = "Autumn 🍂"; break;
default: season = "Invalid month";
}
console.log(`Month ${month} → ${season}`);
🔢 Switch Uses Strict Equality (===)
let value = "1"; // string "1"
switch (value) {
case 1: // number 1
console.log("Number 1 matched");
break;
case "1": // string "1"
console.log("String '1' matched");
break;
default:
console.log("No match");
}
"1" (string) does NOT match 1 (number) in switch — strict comparison!
🧠 Switch(true) Pattern — Range Conditions
You can use switch(true) to evaluate boolean expressions as cases:
let score = 72;
switch (true) {
case score >= 90:
console.log("Grade: A+ 🌟");
break;
case score >= 80:
console.log("Grade: A");
break;
case score >= 70:
console.log("Grade: B");
break;
case score >= 60:
console.log("Grade: C");
break;
default:
console.log("Grade: F");
}
🏗️ Practical Programs
Program 1: HTTP Status Code Handler
let statusCode = 404;
switch (statusCode) {
case 200: console.log("✓ 200 OK - Success"); break;
case 201: console.log("✓ 201 Created"); break;
case 400: console.log("✗ 400 Bad Request"); break;
case 401: console.log("✗ 401 Unauthorized"); break;
case 403: console.log("✗ 403 Forbidden"); break;
case 404: console.log("✗ 404 Not Found"); break;
case 500: console.log("✗ 500 Internal Server Error");break;
default: console.log("? Unknown status:", statusCode);
}
Program 2: Role-Based Access Control
let role = "editor";
switch (role) {
case "admin":
console.log("Access: FULL");
console.log("Permissions: Create, Read, Update, Delete");
break;
case "editor":
console.log("Access: PARTIAL");
console.log("Permissions: Create, Read, Update");
break;
case "viewer":
console.log("Access: READ ONLY");
console.log("Permissions: Read");
break;
default:
console.log("Access: DENIED");
console.log("Unknown role:", role);
}
Access: PARTIAL
Permissions: Create, Read, Update
Program 3: Month Days Counter
let month = 2, year = 2024;
let days;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
days = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28;
break;
default:
days = -1;
}
if (days > 0) {
console.log(`Month ${month}/${year} has ${days} days`);
}
❌ Common Mistakes
Mistake 1: Missing break — Fall-Through Bug
// ❌ WRONG — case "b" falls through to "c"
let grade = "b";
switch (grade) {
case "a": console.log("Excellent");
case "b": console.log("Good"); // matches
case "c": console.log("Average"); // ALSO runs (no break!)
}
// ✅ CORRECT
switch (grade) {
case "a": console.log("Excellent"); break;
case "b": console.log("Good"); break;
case "c": console.log("Average"); break;
}
Mistake 2: Using == Instead of Understanding ===
// Switch ALWAYS uses === (strict equality)
let x = null;
switch (x) {
case undefined:
console.log("undefined"); // null !== undefined
break;
case null:
console.log("null"); // ← matches
break;
}
🧩 Practice Problems
Problem 1: Vowel or Consonant
let letter = "e";
switch (letter.toLowerCase()) {
case "a": case "e": case "i": case "o": case "u":
console.log(`"${letter}" is a VOWEL`);
break;
default:
console.log(`"${letter}" is a CONSONANT`);
}
Problem 2: Traffic Light Controller
let signal = "yellow";
switch (signal) {
case "red": console.log("🔴 STOP"); break;
case "yellow": console.log("🟡 GET READY"); break;
case "green": console.log("🟢 GO"); break;
default: console.log("❓ Unknown signal");
}
🎤 Interview Questions
Q1. What is the switch statement and when should you use it? > switch evaluates a single expression and matches it against multiple cases. Use it when comparing one variable against many specific values — it's cleaner than a long if-else if chain.
Q2. What comparison operator does switch use? > Switch uses strict equality (===) — both value and type must match. "1" === 1 is false, so a string "1" won't match a numeric case 1.
Q3. What happens if you forget break in a switch case? > Execution "falls through" to the next case and continues running until a break is found or the switch ends. This is usually a bug, but can be used intentionally to group cases with the same behavior.
Q4. What is the purpose of the default clause? > default is the catch-all that runs when no case matches the expression. It's optional but recommended. It's like the else in an if-else chain.
Q5. Can default be placed anywhere in switch? > Yes! default can technically go anywhere, but by convention it's placed last for readability.
Q6. Can switch handle ranges (e.g., score 80-90)? > Not directly. Use switch(true) with boolean expressions in cases, or use if-else if for range checks.
Q7. What's the difference between switch and if-else? > Switch is cleaner for multiple exact value comparisons on one variable. if-else is more flexible for ranges, complex conditions, or different variables.
Q8. What is the output?
switch (2) {
case 1: console.log("one");
case 2: console.log("two");
case 3: console.log("three");
}
two and three — falls through without break.
🔑 Key Takeaways
| Concept | Detail |
|---|
| Comparison type | Strict equality (===) |
break purpose | Stops fall-through, exits switch |
default | Runs when no case matches (optional) |
| Fall-through | Intentional grouping of cases |
switch(true) | Evaluates boolean expressions in cases |
| Best for | Exact value matching on one variable |
| Avoid for | Range checks, complex multi-variable conditions |
💡 Remember: Always add break after each case unless you intentionally want fall-through. Missing break is the #1 switch bug!