The switch statement in JavaScript provides a clear, concise way to perform different actions based on multiple possible values of an expression. It is often preferred over multiple if...else if conditions when checking one variable against many values.

💡 Why Use Switch?
Switch statements improve code readability and organization when handling many discrete cases for the same variable or expression.
Basic Syntax
The structure consists of the switch keyword, an expression to evaluate, and one or more case labels with corresponding code blocks:
📌 Deep Dive: Simple Switch
switch (expression) {
case value1:
// code to run if expression === value1
break;
case value2:
// code to run if expression === value2
break;
default:
// code to run if no case matches
}
- expression: the value evaluated once.
- case value: compares expression using strict equality (
===). - break;: exits the switch to prevent fall-through.
- default: optional, runs if no case matches.
Important Details
⚠️ Beware of Fall-Through
If you omit break; at the end of a case, execution continues into the next case regardless of the expression value.
This behavior can be useful but often causes bugs if unintentional.
📌 Deep Dive: Fall-Through Behavior
const fruit = "apple";
switch (fruit) {
case "apple":
console.log("Apple selected");
case "banana":
console.log("Banana selected");
break;
default:
console.log("No fruit selected");
}
// Output:
// Apple selected
// Banana selected
Banana selected
Using Multiple Cases Together
You can group cases to perform the same action for multiple values by stacking them without breaks:
📌 Deep Dive: Group Cases
const day = "Saturday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("It's a weekday.");
}
// Output:
// It's the weekend!
Comparison with if...else if
| Switch Statement | if...else if |
|---|---|
| Clear structure for multiple discrete values | Flexible conditions beyond simple equality |
Uses strict equality (===) for matching | Can use any boolean expression |
Requires explicit break to prevent fall-through | No fall-through behavior |
| Better readability for many discrete cases | Better for complex condition logic |
💡 Summary
Use switch when you need to compare one value against many possible constants. Remember to include break; unless intentionally using fall-through.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What happens if you omit break; in a switch case?
Question 2 of 2
Which comparison operator does switch use to match cases?
Loading results...