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.β π