A switch statement compares one value against several possible matches and runs the code block for whichever one matches. It's an alternative to a long chain of if...else if statements when you're checking the same variable against many fixed values — a day of the week, a status code, a menu choice.
Basic switch Syntax
const day = "Tuesday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Tuesday":
console.log("Second day in.");
break;
case "Friday":
console.log("Almost the weekend!");
break;
default:
console.log("Just another day.");
}
Output:
Second day in.
JavaScript compares day against each case value using strict equality (===), runs the matching block, and the optional default case catches anything that doesn't match any case.
Why break Matters: Fall-Through Behavior
Without a break statement, execution doesn't stop after a matching case — it "falls through" and keeps running every case below it until it hits a break or reaches the end of the switch. This trips up a lot of beginners.
const fruit = "apple";
switch (fruit) {
case "apple":
console.log("It's an apple.");
case "banana":
console.log("It's a banana."); // runs too — no break above!
break;
default:
console.log("Unknown fruit.");
}
Output:
It's an apple.
It's a banana.
Fall-through isn't always a bug, though — it's sometimes used intentionally to group multiple cases that should share the same behavior:
const month = "July";
switch (month) {
case "June":
case "July":
case "August":
console.log("It's summer.");
break;
default:
console.log("Not summer.");
}
Output:
It's summer.
When to Use switch vs if...else
Reach for switch when you're testing one variable against many specific, known values — it reads more cleanly than a long else if chain. Stick with if...else (or a ternary operator for simple cases) when your conditions involve ranges, multiple variables, or complex boolean logic that a switch can't express well.
