switch
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.
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
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.
let day = "sun";
switch (day) {
case "sat":
case "sun":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
// → Weekend
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.
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.
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.
Now you try
- Choose a value with
switch, then share one action between two cases. - Press Check answer to test it.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
let size = "M". Use a switch to log small for "S", medium for "M", large for "L", and unknown otherwise.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Write a function dayType(day) that returns "weekend" for "sat" or "sun", and "weekday" for anything else. Use one switch with two stacked cases.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Write points(medal): 3 for "gold", 2 for "silver", 1 for "bronze", 0 for anything else.
Haz clic en Ejecutar para ver la salida aquí.