Switch statements
Overview
When you compare one value against many possibilities, switch can be easier to read than a long else if chain.
const status = 'paused';
switch (status) {
case 'playing':
console.log('Now playing');
break;
case 'paused':
console.log('Paused');
break;
default:
console.log('Stopped');
}Compare it with the equivalent if chain, which repeats status === on every line:
if (status === 'playing') {
console.log('Now playing');
} else if (status === 'paused') {
console.log('Paused');
} else {
console.log('Stopped');
}How switch works
- JavaScript evaluates the expression in
switch ( … )once. - It compares the result with each
casevalue using===, from top to bottom. - At the first match, it starts running code from that case.
- It keeps running — through any following cases — until it reaches a
break, areturn, or the end of theswitch. - If nothing matches, it runs the
defaultblock (if there is one).
Because the comparison is strict, types must match:
switch ('1') {
case 1:
console.log('number one'); // not reached — '1' !== 1
break;
case '1':
console.log('string one'); // runs
break;
}Fall-through
Each case runs until it reaches break or return. This is called fall-through. Leaving break out on purpose lets several cases share code:
switch (fruit) {
case 'lemon':
case 'lime':
console.log('Sour!');
break;
default:
console.log('Tasty.');
}Forgetting
breakis a classic bug — the next case runs too. Inside a function, usingreturnin each case avoids it.
Here’s what the bug looks like:
const level = 'gold';
switch (level) {
case 'gold':
console.log('Free shipping');
case 'silver':
console.log('10% off');
default:
console.log('Thanks for shopping');
}
// Free shipping, 10% off, Thanks for shopping — all three!If you ever do want fall-through between cases that have code, leave a comment such as // falls through so readers know it’s deliberate.
Returning from cases
Inside a function, return both produces a value and leaves the switch (and the function), so you don’t need break:
function shippingCost(zone) {
switch (zone) {
case 'local':
return 0;
case 'national':
return 49;
case 'international':
return 499;
default:
throw new Error(`Unknown zone: ${zone}`);
}
}Throwing an error in default is a good habit when every valid value should be covered — a typo such as 'nationl' fails loudly instead of silently doing the wrong thing.
Variables inside cases
All the cases share one block, so declaring the same const name in two cases is an error. Wrap a case’s code in its own braces to give it a private scope:
switch (shape) {
case 'circle': {
const area = Math.PI * r ** 2;
console.log(area);
break;
}
case 'square': {
const area = side ** 2; // fine — a separate block
console.log(area);
break;
}
}Matching ranges with switch (true)
switch only checks equality, so it can’t directly test ranges like “score above 90”. A trick you’ll sometimes see is switch (true), where each case is a condition:
switch (true) {
case score >= 90:
grade = 'A';
break;
case score >= 75:
grade = 'B';
break;
default:
grade = 'C';
}It works, but most developers find an if…else if chain clearer for ranges.
An object lookup instead
If each case just produces a value, a plain object is often shorter:
const icons = { playing: '▶', paused: '⏸', stopped: '⏹' };
const icon = icons[status] ?? '?';The object acts as a table: keys on the left, results on the right. The ?? provides a fallback, like default. Lookups can hold functions, too:
const handlers = {
save: () => saveDocument(),
open: () => openDialog(),
quit: () => closeApp(),
};
handlers[command]?.();Which should I use?
| Situation | Best choice |
|---|---|
| Two or three outcomes | if…else |
Ranges (> 90, < 0) |
if…else if |
| One value against many fixed values, each running some code | switch |
| One value mapped straight to another value | Object lookup (or a Map) |
Day type
Use switch to return 'weekend' for 'Sat' and 'Sun', 'midweek' for 'Wed', and 'weekday' for everything else.
function dayType(day) {
// your code here
}function dayType(day) {
switch (day) {
case 'Sat':
case 'Sun':
return 'weekend';
case 'Wed':
return 'midweek';
default:
return 'weekday';
}
}Summary
switchcompares one value with===against eachcase, from top to bottom.- Without
break(orreturn), execution falls through to the next case. - Stacking empty cases lets several values share the same code.
defaultruns when nothing matches — always include one.- For simple value-to-value mapping, an object lookup is often clearer.