Choosing from Multiple Options
The switch statement replaces a long chain of if..else if. It makes the code cleaner and more readable when you need to compare a single variable against multiple values.
1. The Basics
switch (role) {
case 'admin':
alert('Hello, boss!');
break;
case 'guest':
alert('Access denied');
break;
default:
alert('Who are you?');
}
2. Grouping Cases
Multiple cases can execute the same code:
switch (browser) {
case 'Edge':
case 'Chrome':
case 'Firefox':
alert('Ok, we support it');
break;
}
Important
Types matter! Switch uses strict equality ===. If the variable holds the string "1", and the case has the number 1, the condition WILL NOT trigger.
Warning
If you forget the break, execution will continue (fall through) all subsequent case blocks until it hits the first break or the end of the switch block.