Switch Case
An Alternative to the Ladder
When you have a single variable or expression and you need to compare it against a long list of specific values, writing a massive If-Else ladder can get messy and hard to read.
The switch statement provides a cleaner way to handle this scenario.
Syntax and Example
Let's say we want to print the name of the day based on a number (1-7):
let dayNumber = 3;
let dayName;
switch (dayNumber) {
case 1:
dayName = "Monday";
break; // Crucial! Stops the switch from continuing to run
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
default:
dayName = "Invalid Day";
}
console.log(dayName); // Outputs: "Wednesday"
The Importance of break
Notice the break keyword at the end of each case. If you forget to include it, JavaScript will execute the matching case, but then it will "fall through" and automatically execute all the remaining cases below it, regardless of whether they match!
The default Case
The default case acts like the final else in an If-Else ladder. It runs if none of the specific case values match your expression.
💡 Himanshu's Tip:
Always remember your break statements! Without them, your code will 'fall through' and execute every single case below the matching one. It's the most common bug developers face when writing switch statements.
Interview Questions
- What is the purpose of the
breakkeyword in a switch statement? - What does the
defaultcase do? - When should you use a switch statement instead of an if-else ladder?