JavaScript Switch
The switch statement compares one value against many possible cases, offering a clean alternative to long chains of else if.
When switch fits better than if...else
When you need to compare a single value against a list of specific options, a switch statement is often more readable than a stack of else if branches. It evaluates one expression once, then jumps to the matching case. Comparison inside a switch uses strict equality, the same rules as the === operator, so both the value and its type must match.
A simple switch
<!DOCTYPE html>
<html>
<body>
<h2>A simple switch</h2>
<script>
const day = 3;
let name;
switch (day) {
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
case 3:
name = "Wednesday";
break;
default:
name = "Unknown";
}
console.log(name); // "Wednesday"
</script>
</body>
</html>- switch (expression) is evaluated a single time.
- Each case label is compared to that value using strict equality.
- break stops execution and exits the switch once a case is handled.
- default runs when no case matches; it is optional but recommended.
Why break matters
If you forget break, execution continues into the next case even when it does not match. This behavior is called fall-through. It is occasionally useful on purpose, but when it happens by accident it produces confusing bugs, so add break to every case unless you have a clear reason not to.
Deliberate fall-through for shared cases
<!DOCTYPE html>
<html>
<body>
<h2>Deliberate fall-through for shared cases</h2>
<script>
const fruit = "lime";
switch (fruit) {
case "lemon":
case "lime":
console.log("This fruit is sour");
break;
case "banana":
case "mango":
console.log("This fruit is sweet");
break;
default:
console.log("Unknown flavour");
}
// Output: This fruit is sour
</script>
</body>
</html>Here the empty case for "lemon" intentionally falls through to "lime", so both share the same code. Grouping cases this way is the cleanest reason to leave out a break, and it keeps related options together without repeating logic.
Exercise: JavaScript Conditionals
What happens in a switch statement if a matching case has no break?