When you need to check a single value against many possible options, switch statements provide a cleaner alternative to long if/else if chains. They're perfect for handling menu selections, status codes, days of the week, and any scenario where you're comparing one value against multiple possibilities. Let's master switch statements!
What Is a Switch Statement?
A switch statement evaluates an expression once and compares it against multiple case values. When a match is found, the corresponding code block executes.
Think of it like a vending machine:
You select one button (the expression). The machine checks which product matches your selection (the cases) and gives you that specific product (executes that code).
Basic Syntax
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
case value3:
// Code to execute if expression === value3
break;
default:
// Code to execute if no case matches
break;
}Basic Switch Statement
Simple Example
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of work week");
break;
case "Tuesday":
console.log("Second day");
break;
case "Wednesday":
console.log("Midweek");
break;
case "Thursday":
console.log("Almost Friday");
break;
case "Friday":
console.log("Last work day!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Not a valid day");
break;
}
// Output: "Start of work week"How It Works
- JavaScript evaluates the expression in
switch(expression) - It compares the result with each
casevalue using strict equality (===) - When a match is found, the code after that case executes
- The
breakstatement exits the switch - If no case matches, the
defaultcase executes (if present)
The Break Statement
The break statement is crucial in switch statements. It exits the switch block, preventing "fall-through" to the next case.
With Break (Normal Behavior)
let grade = "B";
switch (grade) {
case "A":
console.log("Excellent!");
break; // Exits switch here
case "B":
console.log("Good job!");
break; // Exits switch here
case "C":
console.log("Passed");
break;
default:
console.log("Need improvement");
break;
}
// Output: "Good job!"Without Break (Fall-Through)
let grade = "B";
switch (grade) {
case "A":
console.log("Excellent!");
// No break! Falls through to next case
case "B":
console.log("Good job!");
// No break! Falls through to next case
case "C":
console.log("Passed");
break;
default:
console.log("Need improvement");
break;
}
// Output:
// "Good job!"
// "Passed"
// If grade was "A", output would be:
// "Excellent!"
// "Good job!"
// "Passed"Important: Forgetting break causes fall-through, where execution continues into the next case. This is usually a bug, but can be intentional for grouping cases.
The Default Case
The default case is optional but recommended. It executes when no other case matches—like the else in an if/else statement.
let color = "purple";
switch (color) {
case "red":
console.log("Stop");
break;
case "yellow":
console.log("Caution");
break;
case "green":
console.log("Go");
break;
default:
console.log("Unknown color");
break;
}
// Output: "Unknown color"
// Without default
switch (color) {
case "red":
console.log("Stop");
break;
case "yellow":
console.log("Caution");
break;
case "green":
console.log("Go");
break;
// No default - nothing happens if no match
}
// No outputDefault Placement
// Default typically goes at the end (convention)
switch (value) {
case 1:
console.log("One");
break;
case 2:
console.log("Two");
break;
default:
console.log("Other");
break;
}
// But can be anywhere (works the same)
switch (value) {
default:
console.log("Other");
break;
case 1:
console.log("One");
break;
case 2:
console.log("Two");
break;
}
// Convention: Put default at the end for readability💡 Best Practice:
Always include a default case, even if it just logs an error or does nothing. This makes your code more robust and helps catch unexpected values during development.
Multiple Cases for Same Action
You can group multiple case values that should execute the same code by stacking them without breaks.
// Weekend checker
let day = "Saturday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Workday");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Invalid day");
break;
}
// Output: "Weekend!"
// Season checker
let month = "March";
switch (month) {
case "December":
case "January":
case "February":
console.log("Winter");
break;
case "March":
case "April":
case "May":
console.log("Spring");
break;
case "June":
case "July":
case "August":
console.log("Summer");
break;
case "September":
case "October":
case "November":
console.log("Fall");
break;
default:
console.log("Invalid month");
break;
}
// Output: "Spring"Practical Example: Vowel Checker
function isVowel(letter) {
letter = letter.toLowerCase();
switch (letter) {
case "a":
case "e":
case "i":
case "o":
case "u":
return true;
default:
return false;
}
}
console.log(isVowel("A")); // true
console.log(isVowel("e")); // true
console.log(isVowel("b")); // false
console.log(isVowel("Z")); // falseSwitch vs If/Else
When should you use switch instead of if/else? Here's a comparison.
Same logic, different syntax
If/Else Chain
// Using if/else
let status = "success";
if (status === "success") {
console.log("Operation successful");
} else if (status === "error") {
console.log("An error occurred");
} else if (status === "warning") {
console.log("Warning message");
} else if (status === "info") {
console.log("Information");
} else {
console.log("Unknown status");
}Switch Statement
// Using switch
let status = "success";
switch (status) {
case "success":
console.log("Operation successful");
break;
case "error":
console.log("An error occurred");
break;
case "warning":
console.log("Warning message");
break;
case "info":
console.log("Information");
break;
default:
console.log("Unknown status");
break;
}When to Use Switch
Use switch when:
- Comparing one variable against many specific values
- Values are discrete (strings, numbers, not ranges)
- You have 3+ possible values to check
- You want cleaner, more readable code for many cases
- Cases might need to fall through to each other
When to Use If/Else
Use if/else when:
- Checking different variables or complex conditions
- Using comparison operators (>, <, >=, <=)
- Checking ranges (age >= 18 && age < 65)
- Combining multiple conditions with && or ||
- Conditions are more complex than simple equality
// GOOD use of switch: checking discrete values
switch (userRole) {
case "admin":
grantFullAccess();
break;
case "editor":
grantEditAccess();
break;
case "viewer":
grantViewAccess();
break;
}
// BAD use of switch: ranges require if/else
let age = 25;
switch (true) { // Anti-pattern!
case age < 13:
console.log("Child");
break;
case age < 20:
console.log("Teen");
break;
// This is confusing - use if/else instead
}
// GOOD: Use if/else for ranges
if (age < 13) {
console.log("Child");
} else if (age < 20) {
console.log("Teen");
} else if (age < 65) {
console.log("Adult");
} else {
console.log("Senior");
}Using Return in Switch
Inside functions, you can use return instead of break. This exits both the switch and the function.
// With break
function getDayType(day) {
let type;
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
type = "Weekday";
break;
case "Saturday":
case "Sunday":
type = "Weekend";
break;
default:
type = "Invalid";
break;
}
return type;
}
// With return (cleaner)
function getDayTypeBetter(day) {
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
return "Weekday";
case "Saturday":
case "Sunday":
return "Weekend";
default:
return "Invalid";
}
}
console.log(getDayTypeBetter("Monday")); // "Weekday"
console.log(getDayTypeBetter("Sunday")); // "Weekend"Note: When using return, you don't need break because the function exits immediately. This makes the code cleaner and easier to read.
Switch Uses Strict Equality
Switch statements use strict equality (===), meaning both value and type must match. This is important to remember!
let value = "5"; // String
switch (value) {
case 5: // Number 5
console.log("Number five");
break;
case "5": // String "5"
console.log("String five"); // This executes!
break;
}
// Output: "String five"
// Type matters!
let num = 5;
switch (num) {
case "5":
console.log("This won't execute");
break;
case 5:
console.log("This will execute"); // This one!
break;
}
// If you need loose equality, convert first
let input = "5";
switch (Number(input)) {
case 5:
console.log("Now it matches!"); // Executes
break;
}Practical Examples
Example 1: Calculator
function calculate(num1, num2, operator) {
switch (operator) {
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
if (num2 === 0) {
return "Cannot divide by zero";
}
return num1 / num2;
case "%":
return num1 % num2;
case "**":
return num1 ** num2;
default:
return "Invalid operator";
}
}
console.log(calculate(10, 5, "+")); // 15
console.log(calculate(10, 5, "*")); // 50
console.log(calculate(10, 0, "/")); // "Cannot divide by zero"
console.log(calculate(10, 5, "^")); // "Invalid operator"Example 2: HTTP Status Handler
function handleHTTPStatus(statusCode) {
switch (statusCode) {
case 200:
case 201:
case 204:
return { success: true, message: "Success" };
case 400:
return { success: false, message: "Bad Request" };
case 401:
return { success: false, message: "Unauthorized" };
case 403:
return { success: false, message: "Forbidden" };
case 404:
return { success: false, message: "Not Found" };
case 500:
case 502:
case 503:
return { success: false, message: "Server Error" };
default:
return { success: false, message: "Unknown Status" };
}
}
console.log(handleHTTPStatus(200));
// { success: true, message: "Success" }
console.log(handleHTTPStatus(404));
// { success: false, message: "Not Found" }
console.log(handleHTTPStatus(500));
// { success: false, message: "Server Error" }Example 3: Menu System
function processMenuChoice(choice) {
switch (choice) {
case "1":
case "new":
return startNewGame();
case "2":
case "load":
return loadGame();
case "3":
case "settings":
return openSettings();
case "4":
case "help":
return showHelp();
case "5":
case "quit":
case "exit":
return quitGame();
default:
return "Invalid choice. Please try again.";
}
}
function startNewGame() {
return "Starting new game...";
}
function loadGame() {
return "Loading saved game...";
}
function openSettings() {
return "Opening settings...";
}
function showHelp() {
return "Showing help menu...";
}
function quitGame() {
return "Goodbye!";
}
console.log(processMenuChoice("1")); // "Starting new game..."
console.log(processMenuChoice("new")); // "Starting new game..."
console.log(processMenuChoice("quit")); // "Goodbye!"
console.log(processMenuChoice("99")); // "Invalid choice..."Example 4: Grade Letter to GPA
function gradeToGPA(grade) {
// Normalize to uppercase
grade = grade.toUpperCase();
switch (grade) {
case "A+":
case "A":
return 4.0;
case "A-":
return 3.7;
case "B+":
return 3.3;
case "B":
return 3.0;
case "B-":
return 2.7;
case "C+":
return 2.3;
case "C":
return 2.0;
case "C-":
return 1.7;
case "D+":
return 1.3;
case "D":
return 1.0;
case "F":
return 0.0;
default:
return null;
}
}
console.log(gradeToGPA("A")); // 4.0
console.log(gradeToGPA("B+")); // 3.3
console.log(gradeToGPA("c")); // 2.0 (normalized to uppercase)
console.log(gradeToGPA("Z")); // nullSwitch Statement Practice
Experiment with different switch patterns
console.log() to see your output in the console above.Common Mistakes
1. Forgetting Break
// WRONG: Forgot break
let grade = "B";
switch (grade) {
case "A":
console.log("Excellent!");
case "B":
console.log("Good!"); // Executes
case "C":
console.log("OK"); // Also executes! (fall-through)
break;
}
// Output: "Good!" and "OK"
// RIGHT: Add break
switch (grade) {
case "A":
console.log("Excellent!");
break;
case "B":
console.log("Good!");
break; // Stops here
case "C":
console.log("OK");
break;
}
// Output: "Good!" only2. Type Mismatch
// WRONG: String vs Number
let input = "5"; // String from user input
switch (input) {
case 5: // Number
console.log("Five"); // Won't execute!
break;
}
// RIGHT: Convert or match type
switch (Number(input)) {
case 5:
console.log("Five"); // Now it works!
break;
}
// Or match the string
switch (input) {
case "5":
console.log("Five"); // Works!
break;
}3. Forgetting Default
// RISKY: No default case
let status = "unknown";
switch (status) {
case "success":
console.log("Success");
break;
case "error":
console.log("Error");
break;
// No default - unexpected values do nothing
}
// No output - fails silently!
// BETTER: Add default
switch (status) {
case "success":
console.log("Success");
break;
case "error":
console.log("Error");
break;
default:
console.log("Unknown status:", status); // Catches unexpected values
break;
}Key Takeaways
- Switch statements compare one value against multiple cases
- Use
breakto exit after each case (prevents fall-through) - The
defaultcase handles unmatched values - Switch uses strict equality (
===) for comparisons - Stack cases without breaks to handle multiple values the same way
- Use
returninstead ofbreakinside functions - Switch is cleaner than if/else for checking discrete values
- Use if/else for ranges and complex conditions
- Always include
defaultcase for unexpected values - Watch out for type mismatches (string vs number)
What's Next?
You now know how to use switch statements to handle multiple conditions cleanly! Switch statements are particularly useful for handling user selections, status codes, and any scenario where you're checking one value against many options.
In the next lesson, we'll revisit the Ternary Operatorin more depth—a concise way to write simple if/else statements in a single line. Perfect for quick conditional assignments and inline conditions!
💪 Practice Challenge:
Before moving on, try creating:
- A function that converts number grades (1-7) to letter grades (A-F)
- A command processor that handles different user commands (help, start, stop, etc.)
- A currency converter that handles multiple currency codes (USD, EUR, GBP, etc.)
- A game controller that processes different button presses (up, down, left, right, A, B)
- A status message generator for different HTTP status codes