JavaScript Tutorial · Control Flow · Lesson 15 of 44
JavaScript Switch
Choose between many cases with switch — and don't forget break.
switch
switch compares one value against several cases using strict equality (===):
const day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
Output
Wednesday
break and fall-through
Without break, execution falls through into the next case. That is occasionally useful for grouping cases, but forgetting break is a common bug:
function kind(day) {
switch (day) {
case "Sat":
case "Sun":
return "weekend";
default:
return "weekday";
}
}
console.log(kind("Sun"), kind("Tue"));
Output
weekend weekday
An object lookup alternative
For simple value-to-value mappings, an object is often clearer than a switch:
const httpStatus = { 200: "OK", 404: "Not Found", 500: "Server Error" };
const code = 404;
console.log(httpStatus[code] ?? "Unknown");
Output
Not Found
Test yourself
Which comparison does switch use to match cases?
== (loose equality)=== (strict equality)Object.is only> and <
Show answer
Answer: === (strict equality)