← JS Mastery | Module 2: Control Flow Switch Statements
Module 2

Switch Statements

⏱ 12 min read ● Beginner 🆓 Free

When to Use Switch

A switch statement is an alternative to long if/else chains when you're checking one value against multiple specific cases. It's cleaner and often more readable when you have 3+ branches based on a single variable.

const day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of work week");
    break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
    console.log("Midweek");
    break;
  case "Friday":
    console.log("TGIF!");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend!");
    break;
  default:
    console.log("Invalid day");
}
⚠️ The break keyword is critical

Without break, JavaScript "falls through" to the next case and keeps executing code. This is almost always a bug. Always add break (or return in a function) at the end of each case.

Switch vs If/Else

// Switch uses === for comparison (strict equality)
switch ("5") {
  case 5:
    console.log("number 5");
    break;
  case "5":
    console.log("string '5'");  // This runs
    break;
}

// Fall-through is sometimes intentional:
function getDaysInMonth(month) {
  switch(month) {
    case 2:
      return 28;
    case 4: case 6: case 9: case 11:
      return 30;
    default:
      return 31;
  }
}

// Modern approach — object lookup (often cleaner than switch):
const dayMessages = {
  Monday: "Start of work week",
  Friday: "TGIF!",
  Saturday: "Weekend!",
  Sunday: "Weekend!"
};
const message = dayMessages[day] || "Midweek";

Switch with Return in Functions

// In functions, return exits — no need for break
function getStatusMessage(statusCode) {
  switch (statusCode) {
    case 200: return "OK";
    case 201: return "Created";
    case 400: return "Bad Request";
    case 401: return "Unauthorized";
    case 403: return "Forbidden";
    case 404: return "Not Found";
    case 500: return "Internal Server Error";
    default: return `Unknown status: ${statusCode}`;
  }
}

console.log(getStatusMessage(404)); // "Not Found"
console.log(getStatusMessage(200)); // "OK"

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Write a switch-based calculator function that takes two numbers and an operator (+, -, *, /). Handle division by zero in the default case.

EXERCISE 2

Rewrite the same calculator using an object lookup instead of switch. Which do you find more readable?

← If/Else