Welcome back! š In the previous lesson, you learned the ternary operator for writing clean one-line conditionals. Now let's explore the switch case statement ā JavaScript's most elegant tool for matching one value against many exact options!
The switch statement is like a menu selector. Instead of writing a long chain of if...else if conditions, you hand JavaScript one value and let it jump straight to the right case. The result? Code that's cleaner, easier to scan, and simpler to maintain.
Let's master it from the ground up!
What is a Switch Statement?
A switch statement takes a single expression, evaluates it once, and then compares the result against a list of case values. When a match is found, the code inside that case runs.
The Problem it Solves
Imagine checking the day of the week with if...else if:
// ā Long and repetitive
let day = "Wednesday";
if (day === "Monday") {
console.log("Start of the work week! šŖ");
} else if (day === "Tuesday") {
console.log("Second day!");
} else if (day === "Wednesday") {
console.log("Midweek! š
");
} else if (day === "Thursday") {
console.log("Almost there!");
} else if (day === "Friday") {
console.log("Last work day! š");
} else {
console.log("Weekend! š");
}Now with switch:
// ā
Clean and easy to read
let day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the work week! šŖ");
break;
case "Tuesday":
console.log("Second day!");
break;
case "Wednesday":
console.log("Midweek! š
");
break;
case "Thursday":
console.log("Almost there!");
break;
case "Friday":
console.log("Last work day! š");
break;
default:
console.log("Weekend! š");
}
// Output: Midweek! š
Same logic ā but the switch version is far easier to scan and extend.
Syntax
switch (expression) {
case value1:
// code to run if expression === value1
break;
case value2:
// code to run if expression === value2
break;
case value3:
// code to run if expression === value3
break;
default:
// code to run if no case matches
}Key Parts Explained
switch (expression)ā the value being tested; evaluated oncecase value:ā a candidate to match against; uses strict equality (===)breakā stops execution and exits the switch blockdefaultā optional fallback that runs when no case matches (likeelse)
How JavaScript Evaluates a Switch
Understanding the internal flow helps you avoid bugs.
let fruit = "Mango";
switch (fruit) {
case "Apple":
console.log("š Apple"); // ā "Mango" !== "Apple" ā skip
break;
case "Banana":
console.log("š Banana"); // ā "Mango" !== "Banana" ā skip
break;
case "Mango":
console.log("š„ Mango!"); // ā
Match found ā run this
break;
case "Grapes":
console.log("š Grapes"); // Never reached
break;
default:
console.log("Unknown fruit"); // Never reached
}
// Output: š„ Mango!JavaScript checks each case from top to bottom until it finds a strict match, then runs that block. Once break is hit, it exits the entire switch.
The break Keyword
break is what stops JavaScript from running into the next case. Without it, execution falls through to the next case automatically ā whether or not it matches.
Without break (Fall-Through Bug ā)
let num = 1;
switch (num) {
case 1:
console.log("One");
// ā No break ā falls into case 2
case 2:
console.log("Two");
// ā No break ā falls into case 3
case 3:
console.log("Three");
break;
}
// Output:
// One
// Two
// Three ā Unintended!With break (Correct ā
)
let num = 1;
switch (num) {
case 1:
console.log("One");
break; // ā
Exit here
case 2:
console.log("Two");
break;
case 3:
console.log("Three");
break;
}
// Output: One ā
The default Case
default is the switch statement's fallback ā it runs when none of the case values match. It's like the else at the end of an if...else if chain.
let color = "purple";
switch (color) {
case "red":
console.log("Red š“");
break;
case "green":
console.log("Green š¢");
break;
case "blue":
console.log("Blue šµ");
break;
default:
console.log(`"${color}" is not a primary color. šØ`);
}
// Output: "purple" is not a primary color. šØdefault Doesn't Have to Be Last
While convention puts default at the bottom, it can go anywhere. However, if it's not last, it still needs a break to prevent fall-through.
let val = 99;
switch (val) {
default:
console.log("No match found");
break; // ā
Still needs break if not last
case 1:
console.log("One");
break;
case 2:
console.log("Two");
break;
}
// Output: No match foundBest practice: Always put default last for readability ā it signals "if nothing else matched, do this."
Intentional Fall-Through
Sometimes fall-through is exactly what you want ā when multiple cases should run the same block of code. Just stack the cases together with no code or break between them.
Grouping Cases
let month = 6; // June
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
console.log("This month has 31 days. š
");
break;
case 4:
case 6:
case 9:
case 11:
console.log("This month has 30 days. š
");
break;
case 2:
console.log("February has 28 or 29 days. š
");
break;
default:
console.log("Invalid month ā");
}
// Output: This month has 30 days. š
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 ā");
}
// Output: Weekend š ā time to relax!Switch Uses Strict Equality (===)
This is one of the most important things to know about switch. It always compares using === ā meaning both value AND type must match.
let value = "1"; // String "1"
switch (value) {
case 1:
console.log("Number 1"); // ā "1" !== 1 (different types!)
break;
case "1":
console.log("String '1'"); // ā
"1" === "1" ā match!
break;
default:
console.log("No match");
}
// Output: String '1'let flag = true;
switch (flag) {
case 1:
console.log("Number 1"); // ā true !== 1 (strict!)
break;
case true:
console.log("Boolean true ā
"); // ā
Match
break;
}
// Output: Boolean true ā
Real-World Examples
Example 1: Traffic Light System
let signal = "yellow";
switch (signal) {
case "red":
console.log("š“ STOP ā Do not proceed.");
break;
case "yellow":
console.log("š” SLOW DOWN ā Prepare to stop.");
break;
case "green":
console.log("š¢ GO ā Proceed safely.");
break;
default:
console.log("ā ļø Unknown signal ā proceed with caution.");
}
// Output: š” SLOW DOWN ā Prepare to stop.Example 2: Calculator
let a = 20;
let b = 5;
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 "/":
if (b === 0) {
console.log("ā Cannot divide by zero!");
} else {
console.log(`${a} / ${b} = ${a / b}`);
}
break;
case "%":
console.log(`${a} % ${b} = ${a % b}`);
break;
default:
console.log(`ā Unknown operator: "${operator}"`);
}
// Output: 20 * 5 = 100Example 3: Language Greeter
let language = "Hindi";
switch (language) {
case "English":
console.log("Hello! š");
break;
case "Hindi":
console.log("Namaste! š");
break;
case "Spanish":
console.log("Ā”Hola! š");
break;
case "French":
console.log("Bonjour! š");
break;
case "Japanese":
console.log("Konnichiwa! š");
break;
default:
console.log(`Greetings! (Language "${language}" not supported yet)`);
}
// Output: Namaste! šExample 4: Subscription Plan Features
let plan = "pro";
switch (plan) {
case "enterprise":
console.log("ā
Custom integrations");
console.log("ā
Dedicated support");
// fall-through intentionally
case "pro":
console.log("ā
Advanced analytics");
console.log("ā
Priority email support");
// fall-through intentionally
case "basic":
console.log("ā
10GB storage");
console.log("ā
Standard features");
break;
default:
console.log("ā No plan selected");
}
// Output:
// ā
Advanced analytics
// ā
Priority email support
// ā
10GB storage
// ā
Standard featuresExample 5: HTTP Status Code Handler
let statusCode = 404;
switch (statusCode) {
case 200:
console.log("200 ā
OK ā Request successful.");
break;
case 201:
console.log("201 ā
Created ā Resource created.");
break;
case 301:
console.log("301 š Moved Permanently ā Redirect.");
break;
case 400:
console.log("400 ā Bad Request ā Check your input.");
break;
case 401:
console.log("401 š Unauthorized ā Please log in.");
break;
case 403:
console.log("403 š« Forbidden ā Access denied.");
break;
case 404:
console.log("404 š Not Found ā Page doesn't exist.");
break;
case 500:
console.log("500 š„ Internal Server Error ā Try again later.");
break;
default:
console.log(`${statusCode} ā Unknown status code.`);
}
// Output: 404 š Not Found ā Page doesn't exist.Switch vs if...else if ā When to Use Which
Both can solve the same problems, but each shines in different situations.
| Feature | switch | if...else if |
|---|---|---|
| Best for | Matching exact values | Checking ranges or complex expressions |
| Comparison type | Strict equality === only | Any expression |
| Readability | Cleaner for many exact cases | Better for 2ā3 conditions |
| Multiple cases, same code | Easy ā just stack cases | Requires ` |
Range checks (> < >=) | ā Not supported | ā Native |
| Performance | Slightly faster for many cases | Fine for fewer cases |
Use switch When:
// Matching exact string values ā
switch (command) {
case "start": ...
case "stop": ...
case "pause": ...
}
// Matching exact number values ā
switch (errorCode) {
case 404: ...
case 500: ...
}Use if...else if When:
// Range comparisons ā
if (score >= 90) { ... }
else if (score >= 75) { ... }
// Complex conditions ā
if (age > 18 && hasLicense) { ... }
else if (age > 16 && hasPerm) { ... }Switch Inside a Function
A common and clean pattern ā wrap your switch in a function and return from each case instead of using break.
function getDayType(day) {
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
return "Weekday š¼";
case "Saturday":
case "Sunday":
return "Weekend š";
default:
return "Invalid day ā";
}
}
console.log(getDayType("Monday")); // Weekday š¼
console.log(getDayType("Saturday")); // Weekend š
console.log(getDayType("Holiday")); // Invalid day āUsing return inside a function automatically exits both the switch and the function ā so break is not needed. This is a very clean and popular pattern.
Common Mistakes
Mistake 1: Forgetting break (Unintended Fall-Through)
let grade = "B";
// ā Missing break ā falls through all cases below B
switch (grade) {
case "A":
console.log("Excellent!");
case "B":
console.log("Good!"); // Runs ā
case "C":
console.log("Average."); // Also runs ā
default:
console.log("Invalid."); // Also runs ā
}
// Output: Good! Average. Invalid.
// ā
Add break to each case
switch (grade) {
case "A":
console.log("Excellent!");
break;
case "B":
console.log("Good!");
break;
case "C":
console.log("Average.");
break;
default:
console.log("Invalid.");
}
// Output: Good! ā
Mistake 2: Using Switch for Range Checks
let score = 85;
// ā Switch can't do range comparisons ā this won't work as expected
switch (score) {
case score >= 90: // This checks (85 >= 90) = false, not 90
console.log("A");
break;
case score >= 75: // This checks (85 >= 75) = true... but matches true, not score
console.log("B");
break;
}
// Likely output: nothing (no match!)
// ā
Use if...else if for ranges
if (score >= 90) {
console.log("A");
} else if (score >= 75) {
console.log("B");
}Mistake 3: Type Mismatch (Forgetting Strict Equality)
let input = "2"; // String ā from user input or URL param
// ā Type mismatch ā "2" !== 2
switch (input) {
case 2:
console.log("Two"); // Never runs!
break;
default:
console.log("No match"); // Runs instead
}
// ā
Match the correct type
switch (input) {
case "2":
console.log("Two ā
");
break;
default:
console.log("No match");
}
// Or convert first:
switch (Number(input)) {
case 2:
console.log("Two ā
");
break;
}Mistake 4: Missing default Case
let status = "pending"; // Unexpected value
// ā No default ā silent failure, nothing happens
switch (status) {
case "active":
console.log("Active ā
");
break;
case "inactive":
console.log("Inactive š¤");
break;
}
// Output: (nothing ā hard to debug!)
// ā
Always include a default
switch (status) {
case "active":
console.log("Active ā
");
break;
case "inactive":
console.log("Inactive š¤");
break;
default:
console.log(`Unknown status: "${status}" ā ļø`);
}
// Output: Unknown status: "pending" ā ļøMistake 5: Declaring Variables Inside Cases Without Blocks
// ā Variable declarations inside switch cases can leak across cases
switch (action) {
case "greet":
let message = "Hello!"; // Can cause SyntaxError or unexpected behavior
console.log(message);
break;
case "bye":
let message = "Goodbye!"; // ā SyntaxError: 'message' already declared
console.log(message);
break;
}
// ā
Wrap each case in its own block using {}
switch (action) {
case "greet": {
let message = "Hello!"; // Scoped to this block only
console.log(message);
break;
}
case "bye": {
let message = "Goodbye!"; // ā
Different scope ā no conflict
console.log(message);
break;
}
}Practical Exercise: Build a Command Line Menu
Create a file called switch-demo.js:
// šÆ Exercise: Switch Case Practice
// 1. Simple Calculator
function calculate(a, operator, b) {
console.log(`\n=== ${a} ${operator} ${b} ===`);
switch (operator) {
case "+":
console.log(`Result: ${a + b}`);
break;
case "-":
console.log(`Result: ${a - b}`);
break;
case "*":
console.log(`Result: ${a * b}`);
break;
case "/":
b === 0
? console.log("Result: ā Cannot divide by zero")
: console.log(`Result: ${a / b}`);
break;
case "%":
console.log(`Result: ${a % b}`);
break;
default:
console.log(`ā Unknown operator: "${operator}"`);
}
}
calculate(10, "+", 5);
calculate(10, "-", 3);
calculate(6, "*", 7);
calculate(20, "/", 4);
calculate(10, "/", 0);
calculate(10, "^", 2);
// 2. Season Finder
function getSeason(month) {
console.log(`\n=== Month: ${month} ===`);
switch (month) {
case 12:
case 1:
case 2:
console.log("āļø Winter");
break;
case 3:
case 4:
case 5:
console.log("šø Spring");
break;
case 6:
case 7:
case 8:
console.log("āļø Summer");
break;
case 9:
case 10:
case 11:
console.log("š Autumn");
break;
default:
console.log("ā Invalid month. Enter 1ā12.");
}
}
getSeason(1);
getSeason(5);
getSeason(7);
getSeason(10);
getSeason(13);
// 3. Notification Handler
function handleNotification(type, sender) {
let message;
switch (type) {
case "message":
message = `š¬ New message from ${sender}`;
break;
case "like":
message = `ā¤ļø ${sender} liked your post`;
break;
case "follow":
message = `š¤ ${sender} started following you`;
break;
case "comment":
message = `š ${sender} commented on your post`;
break;
case "share":
message = `š ${sender} shared your post`;
break;
default:
message = `š New notification from ${sender}`;
}
console.log(`\nNotification: ${message}`);
}
handleNotification("message", "Priya");
handleNotification("like", "Rahul");
handleNotification("follow", "Sara");
handleNotification("mention", "Arjun");Run it:
node switch-demo.jsExpected Output:
=== 10 + 5 ===
Result: 15
=== Month: 7 ===
āļø Summer
Notification: š¬ New message from Priya
Notification: ā¤ļø Rahul liked your post
Notification: š New notification from ArjunKey Takeaways
Congratulations! š You've fully mastered the switch case statement in JavaScript.
ā
switch statement evaluates one expression and jumps to the matching case.
ā
Strict equality (===):
- Switch always uses
===ā type AND value must match "1"and1are different cases
ā
break keyword:
- Exits the switch block after a case runs
- Without
break, execution falls through to the next case
ā
default case:
- Optional but always recommended
- Runs when no case matches ā your safety net
ā Intentional fall-through:
- Stack multiple cases with no code between them
- All grouped cases run the same block
ā
return in functions:
- Inside a function,
returnreplacesbreakā cleaner pattern
ā Switch vs if...else if:
- Use
switchfor exact value matching - Use
if...else iffor ranges and complex conditions
ā Variable declarations in cases:
- Wrap each case in
{}blocks when declaringletorconst
Best Practices
- ā
Always add
breakat the end of every case (unless intentional fall-through) - ā
Always include a
defaultcase ā never let a switch fail silently - ā
Use
{}blocks inside cases when declaringletorconst - ā
Place
defaultlast for readability and convention - ā
Use
returninstead ofbreakwhen switch is inside a function - ā
Never use switch for range comparisons ā use
if...else ifinstead - ā Watch out for type mismatches ā convert input types before switching
- ā Add a comment when using intentional fall-through so it's clear to other developers
What's Next?
Excellent work! š You've now completed the entire Conditional Statements series:
- ā Conditional Statements (overview)
- ā If Else Ladder
- ā Ternary Operator
- ā Switch Case
Up next, we're moving into Loops in JavaScript ā where you'll learn how to run code repeatedly without writing it over and over. Get ready for for, while, and for...of loops!
Keep up the great momentum! šŖ