switch
switch compares one value against a list of cases, which reads more clearly than a long chain of else if when you're matching exact values.
JavaScript
const day = "Sat";
switch (day) {
case "Mon":
case "Tue":
case "Wed":
case "Thu":
case "Fri":
console.log("Weekday");
break;
case "Sat":
case "Sun":
console.log("Weekend!");
break;
default:
console.log("Not a day");
}- Each
caseis compared with===(strict equality). - Stacking several
caselabels lets them share one block. defaultruns when nothing matches, like a finalelse.
Don't forget break
Without break, execution falls through into the next case:
JavaScript
const level = 2;
switch (level) {
case 1:
console.log("Level 1 perks");
case 2:
console.log("Level 2 perks");
case 3:
console.log("Level 3 perks");
}Level 2 printed the perks for 2 and 3. Occasionally that's intended; usually it's a bug. Always end each case with break (or return inside a function).
Returning from a switch
Inside a function, return ends the case and the function at once:
JavaScript
function shippingDays(method) {
switch (method) {
case "express": return 1;
case "standard": return 4;
case "economy": return 8;
default: return null;
}
}
console.log(shippingDays("express"), shippingDays("economy"), shippingDays("drone"));An object lookup is often cleaner
For a simple "value to value" mapping, an object does the same job with less code:
JavaScript
const shippingDays = { express: 1, standard: 4, economy: 8 };
const method = "standard";
console.log(shippingDays[method] ?? "unknown method");Ranges need switch (true)
switch only matches exact values. For ranges, use if/else if, or the switch (true) trick:
JavaScript
const score = 82;
let grade;
switch (true) {
case score >= 90: grade = "A"; break;
case score >= 75: grade = "B"; break;
case score >= 50: grade = "C"; break;
default: grade = "F";
}
console.log(grade);Finished this lesson?Mark it complete to earn +20 XP and move your progress on.