Discrete Choices
Use switch when you compare one value against many fixed cases.
It can be cleaner than a long else-if ladder when all checks are equality checks.
JavaScript Tutorial
The switch statement is a clean way to choose between many fixed outcomes.
It compares a single value against multiple cases and runs the first match.
Long else-if chains can be hard to read when every branch checks the same variable.
Switch keeps that pattern compact and easy to scan.
switch (value) { case x: ...; break; default: ... }const role = "editor";
switch (role) {
case "admin":
console.log("All access");
break;
case "editor":
console.log("Write access");
break;
default:
...Switch matches the value to one of the cases.
const day = "sat";
switch (day) {
case "sat":
case "sun":
console.log("Weekend");
break;
default:
console.log("Weekday");
}Group cases when they share the same behavior.
Use switch when you compare one value against many fixed cases.
It can be cleaner than a long else-if ladder when all checks are equality checks.
If you omit `break`, execution continues into the next case. This is called fall-through.
Sometimes it is useful, but it is a common source of bugs.
The default block runs when no case matches.
Always include a default to handle unexpected values.
const status = 404;
switch (status) {
case 200:
console.log("OK");
break;
case 404:
console.log("Not Found");
break;
default:
...Switch works with numbers, strings, and more.
const size = "M";
let price = 0;
switch (size) {
case "L":
price += 2;
case "M":
price += 1;
case "S":
price += 0;
...Without breaks, cases fall through. Use carefully.
Without
if (role === "admin") {
console.log("All access");
} else if (role === "editor") {
console.log("Write access");
} else {
console.log("Read access");
}With
switch (role) {
case "admin":
console.log("All access");
break;
case "editor":
console.log("Write access");
break;
default:
console.log("Read access");
}Add break to avoid unexpected fall-through.
Always include default for unexpected values.
Switch is best for equality checks on one value.
Switch uses strict equality (===), so types must match.
It uses strict equality (===) against each case.
When one case continues into the next because break is missing.
When comparing one value to many fixed cases.
Practice: Use switch to map a plan name to a monthly price.
const plan = "pro";
// TODO: log price for basic, pro, or enterprise
One Possible Solution
const plan = "pro";
switch (plan) {
case "basic":
console.log(10);
break;
case "pro":
console.log(25);
break;
case "enterprise":
console.log(50);
break;
default:
console.log(0);
}Yes, switch compares using ===.
Yes, but they are matched against the switch value.
No, it can be useful for grouped cases, but use it intentionally.
Try different values to see how switch selects a case.