JavaScript
This page explains how switch compares one value with several fixed choices using case, break, and default.
Goal: choose clear branches for one value and avoid accidental fall-through.
switch
Use switch when one expression should be compared with several known values. Each case names one possible value, and default handles everything else.
JavaScript
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Almost the weekend");
break;
default:
console.log("Another day");
}What each part does
switch (expression)- Evaluates the value to compare.
case value:- Matches a fixed value and starts that block.
break- Leaves the switch after the matching block.
default:- Runs when no case matches. It is optional.
Fall-through can be intentional
Without break, execution continues into the next case. This is called fall-through. You can use it deliberately when several values share one action, but make the intent clear.
JavaScript
switch (role) {
case "admin":
case "editor":
console.log("May edit");
break;
default:
console.log("Read only");
}switch or if?
Use switch for one value and several fixed matches. Use if / else if for ranges, compound conditions, or comparisons such as score >= 80.