A switch statement compares one value against a list of possible matches. It is a tidy alternative to a long if / else if chain when you always test the same variable.
const day = "tue";
switch (day) {
case "mon":
console.log("Start of the week");
break;
case "tue":
console.log("Second day"); // → Second day
break;
case "sat":
case "sun":
console.log("Weekend");
break;
default:
console.log("Some other day");
}
How it works
- JavaScript evaluates the expression in
switch (...)once. - It compares the result with each
caseusing strict equality (===). - It runs the code after the first matching case.
breakjumps out of the switch.defaultruns when nothing matched.
Do not forget break
Without break, execution falls through into the next case.
const level = 1;
switch (level) {
case 1:
console.log("one");
case 2:
console.log("two (fell through)");
break;
case 3:
console.log("three");
}
The output has two lines, because level 1 had no break. Fall-through is useful on purpose (see sat and sun above, where two cases share one block), but it is also an easy mistake.
Returning from a switch
Inside a function, return replaces break:
function statusText(code) {
switch (code) {
case 200: return "OK";
case 404: return "Not found";
case 500: return "Server error";
default: return "Unknown";
}
}
console.log(statusText(404)); // → Not found
switch or if?
- Use
switchwhen comparing one value against several exact matches. - Use
if / else iffor ranges and mixed conditions (score >= 90). - For a lookup that just maps a key to a value, an object is often neater:
const messages = { 200: "OK", 404: "Not found", 500: "Server error" };
console.log(messages[404] ?? "Unknown"); // → Not found
Scope tip
let variables inside a case, wrap the case body in { } to avoid clashes.