switch
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
switch picks a case
switchcompares one value against several possible matches, called cases.- It is a tidy alternative to a long
if … else ifchain that tests the same variable. defaultruns when no case matches, like a finalelse.

English
let day = "sat";
switch (day) {
case "sat":
console.log("Weekend");
break;
case "mon":
console.log("Back to school");
break;
default:
console.log("A school day");
}
// → Weekend
English
break ends the case
breakjumps out of theswitch.- Without it, JavaScript keeps going into the next case. This is called fall-through.
- Fall-through is useful on purpose: stack several cases that share one action.
English
let day = "sun";
switch (day) {
case "sat":
case "sun":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
// → Weekend
English
Worked example: points for a medal
Question: a medal is "gold", "silver" or "bronze". Gold scores 3 points, silver 2, bronze 1, and anything else 0.
let medal = "silver";
let points;
switch (medal) {
case "gold":
points = 3;
break;
case "silver":
points = 2;
break;
case "bronze":
points = 1;
break;
default:
points = 0;
}
console.log(points);
// → 2
The switch only chooses. The single console.log after it prints the result, whichever case ran.
English
Watch out
switchcompares with===. Socase 1does not match the string"1".- A
casetests one exact value. For ranges such as "70 or more", useif … else if.
English
Common mistakes
- Forgetting
break. The next case runs too, and its value overwrites yours. - Writing
case "gold" || "silver":. That is one value,"gold". Stack twocaselines instead. - Putting
defaultabove another case without abreak. It still runs only when nothing matches, but then it falls through into the case below. Keepdefaultlast.
English
Now you try
- Choose a value with
switch, then share one action between two cases. - Press Check answer to test it.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
let size = "M". Use a switch to log small for "S", medium for "M", large for "L", and unknown otherwise.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function dayType(day) that returns "weekend" for "sat" 或 "sun", and "weekday" for anything else. Use one switch with two stacked cases.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write points(medal): 3 for "gold", 2 for "silver", 1 for "bronze", 0 for anything else.
点击“运行”查看此处输出。