Mastering switch...case in JavaScript

🧭 What is switch...case?

The switch statement is a control structure that checks a variable against multiple possible values. It's often used as a cleaner alternative to multiple if...else if statements. πŸ’‘

>>β€œWhen you have many paths, switch helps you pick the right one β€” clearly and cleanly.” 🌈

πŸ“Œ Syntax

Basic switch Syntax

switch (expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // default code block
}

πŸ” Here's what each part means:

  • expression is evaluated once.
  • Each case is compared to the expression.
  • If a match is found, that case's code runs.
  • break stops the switch from continuing to other cases.
  • default is run if no matches are found.

🌐 Example: Weekday Checker

switch Weekday Example

const day = "Monday";

switch (day) {
  case "Monday":
    console.log("πŸ“… Start of the work week!");
    break;
  case "Friday":
    console.log("πŸŽ‰ Last work day of the week!");
    break;
  case "Saturday":
  case "Sunday":
    console.log("😎 It's the weekend!");
    break;
  default:
    console.log("πŸ”„ Regular weekday");
}

βš™οΈ Why Use switch?

switch statements are ideal when:

  • You are checking one value against many possible cases
  • You want cleaner, more readable logic than multiple if...else blocks

🧠 Grouping Cases

You can group multiple case values together without a break to handle them the same way.

Grouped Cases

const fruit = "apple";

switch (fruit) {
  case "apple":
  case "banana":
  case "orange":
    console.log("🍎🍌🍊 It's a fruit!");
    break;
  default:
    console.log("❓ Not a recognized fruit.");
}

⚠️ Important Notes

Note

Always include break unless you explicitly want to fall through to the next case. Forgetting it will run all following cases until a break or end.

Note

The switch uses strict comparison (===), so type must match too!

πŸ“š Further Reading

>>β€œUse switch not just for cleaner code β€” but for code that speaks clearly with every case.” πŸ“–