Concept Explanation
When you have 5 or 10 different conditions to check (like "Days of the Week" or "Menu Options"), using if/else becomes a nightmare of curly brackets.
The switch statement is like a Train Station Dispatcher. It looks at one single value and sends your code down the correct track instantly.
Syntax or Core Structure
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break; // STOP HERE!
case "Friday":
console.log("Almost the weekend.");
break;
default:
console.log("Just another day.");
}
Common Mistakes
- Forgetting the
break: If you forget to typebreak;, JavaScript will "Fall Through" and run the code for the NEXT case too, even if it doesn't match! - Strict Comparison:
switchuses===. If you use a string "1" for a case checking for number 1, it will fail. - Complex Logic: Don't use
switchfor math likescore > 50. It's only good for exact matches like "Value A" or "Value B."
Best Practices
- Always have a
default: Just like anelse, thedefaultcase handles everything you didn't plan for. It's your safety net. - Case Grouping: You can put multiple cases together if they do the same thing:
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
Practice Exercises
- The Month Picker: Write a switch statement that takes a month number (1-12) and prints the name of the month.
- The Robot Assistant: Create a switch statement for a robot that responds to commands: "Clean", "Dance", and "Sleep".
- The Coffee Machine: Build a switch for a machine with options: "Espresso", "Latte", "Cappuccino". Print the price for each.