Loading lessons...
JavaScript Switch
JavaScript Switch
The switch statement picks one of many blocks to run based on a value.
The switch syntax
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("Almost weekend");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek");
}
How it works
- The switch compares the value against each
case. - When a case matches, that code runs.
breakstops the switch from falling through to the next case.defaultruns when nothing matches (like an else).
Fall through
If you forget break, execution continues into the next case. Sometimes this is used on purpose, like the Saturday/Sunday example above.
switch vs if...else
switchis clean for comparing one value against many fixed options.if...elseis better for ranges and complex conditions.
TL;DR
switchruns the matching case.breakstops fall through.defaulthandles no-match situations.- Use switch for many fixed-value comparisons.