JavaScript Tutorial
JavaScript Switch
switch picks a case that === the value. break stops the fall-through. default is the leftover.
Pick a matching case
switch (value) compares value to each case with===. The first matching case runs. It is a readable way to branch on one discrete value: a day name, a status string, a small integer code.
It is not a replacement for ranges. score >= 90 still belongs in if /else if. Switch wants exact matches.
Change the day string in /javascript/try and run again. Misspell it on purpose to see default.
A complete switch
Each case ends with break unless you want the next case to run too.default runs when nothing matched. Put it last.
Example
const day = "Tue";
let label;
switch (day) {
case "Mon":
label = "start of week";
break;
case "Tue":
label = "second day";
break;
case "Fri":
label = "almost weekend";
break;
default:
label = "some other day";
}
console.log(label);
document.body.textContent = label;
Matching uses ===
case 5: does not match the string "5". Switch does not coerce the way== does. Convert the value first if it came from an input, or write the case as a string.
Example
const raw = "2";
let asNumber = "no match";
let asString = "no match";
switch (raw) {
case 2:
asNumber = "matched number 2";
break;
default:
asNumber = "number case missed";
}
switch (raw) {
case "2":
asString = "matched string 2";
break;
default:
asString = "string case missed";
}
console.log(asNumber);
console.log(asString);
document.body.textContent = asNumber + " / " + asString;
break stops fall-through
Without break, execution continues into the next case, even if that case’s label does not match. That is fall-through. It is occasionally useful for grouping cases. It is a bug when you forgetbreak on a case that should stand alone.
Example
const code = "B";
let kind;
switch (code) {
case "A":
case "B":
case "C":
kind = "letter grade";
break;
case "P":
kind = "pass fail";
break;
default:
kind = "unknown";
}
console.log(kind);
document.body.textContent = kind;
"A", "B", and "C" share one body on purpose. The empty cases fall through to "C"’s block, then break leaves the switch.
default is the leftover
If you omit default and nothing matches, the switch does nothing. That can leave a variable unset. Give default a safe message, or set the variable before the switch.
| Piece | Job |
|---|---|
switch (value) | Choose what to compare |
case x: | Run when value === x |
break | Leave the switch now |
default | Run when no case matched |
Switch versus if
Use switch when one value has several exact labels. Use if when you test ranges, combine conditions with &&, or compare two different variables. Both are valid. Readability decides.
What to remember
- Cases match with
===, not==. - End a standalone case with
break. - Fall-through is real. Group cases only on purpose.
defaulthandles unknown values.
Next: for loops — repeat with a counter, or walk values with for...of.