36. Control Flow: The switch Statement
The switch statement is an alternative to long if...else if chains when you are comparing a single expression against multiple possible constant values.
Syntax
javascript switch (expression) { case value1: // Code if expression === value1 break; case value2: // Code if expression === value2 break; default: // Code if no match is found }
Example: Day of the Week
javascript let day = 'Wednesday'; let type;
switch (day) { case 'Saturday': case 'Sunday': type = 'Weekend'; break; case 'Wednesday': type = 'Mid-Week'; break; default: type = 'Weekday'; }
console.log(day + ' is a ' + type); // Output: Wednesday is a Mid-Week
The Crucial break Keyword
If you omit break, the execution will 'fall through' to the next case, regardless of whether it matches. This is rarely desired and is the most common beginner mistake with switch statements.