In short
The JavaScript switch statement compares one value against many possible cases. Learn its syntax, why break matters, how default works and when to choose switch, if/else or an object. What is a switch statement? Imagine a vending machine.
The JavaScript switch statement compares one value against many possible cases. Learn its syntax, why break matters, how default works and when to choose switch, if/else or an object.
What is a switch statement?
Imagine a vending machine. You press a number, and the machine gives you the drink that matches that number. A switch statement works the same way: it takes one value and jumps to the case that matches it.
It's a clean alternative to a long chain of else if checks that all compare the same variable against different values.
JavaScript switch syntax with break and default
const orderStatus = 'shipped';
switch (orderStatus) {
case 'pending':
console.log('We received your order.');
break;
case 'shipped':
console.log('Your order is on the way!');
break;
case 'delivered':
console.log('Your order has arrived. Enjoy!');
break;
default:
console.log('Unknown status. Please contact support.');
}
// Output: Your order is on the way!
How it works, part by part:
switch (orderStatus)is the value you want to check.- Each
case 'shipped':is one possible value. JavaScript compares using strict equality, like===, so the type must match too. - The code after the matching
caseruns. break;means "stop here and leave the switch".default:runs when no case matches. It's like theelseat the end of an if chain. It is optional, but it's good practice to include it.
Common mistake: Forgetting
break. Without it, JavaScript doesn't stop at the end of the matching case. It keeps running the code of all the cases below, even if they don't match. This is called fall-through.
Here is what happens when break is missing:
const level = 'beginner';
switch (level) {
case 'beginner':
console.log('Start with the basics.');
case 'intermediate':
console.log('Practice with projects.');
case 'advanced':
console.log('Learn design patterns.');
}
// Output:
// Start with the basics.
// Practice with projects.
// Learn design patterns.
Only the first case matched, but all three messages appear, because nothing told JavaScript to stop.
Using fall-through on purpose
Fall-through is usually a bug, but it's useful when several values should run the same code. You stack the cases on top of each other with no code between them.
This example uses new Date().getDay(), which gives the day of the week as a number: 0 for Sunday, 1 for Monday, up to 6 for Saturday.
const day = new Date().getDay();
let openingHours;
switch (day) {
case 0:
case 6:
openingHours = '10:00 to 16:00 (weekend)';
break;
case 5:
openingHours = '9:00 to 20:00 (late opening on Friday)';
break;
default:
openingHours = '9:00 to 18:00';
}
console.log(`Today we are open ${openingHours}.`);
// Output (on a Saturday): Today we are open 10:00 to 16:00 (weekend).
case 0: has no code and no break, so it falls through into case 6:. Sunday and Saturday share the same hours. Monday to Thursday don't match any case, so they use default.
Tip: When you use fall-through on purpose between cases that do have code, add a comment like
// falls throughso other developers know it's intentional.
switch vs if/else vs an object lookup
All three can make choices. Here's when to use each one:
| Use | When | Example |
|---|---|---|
if / else if | Conditions are ranges or combine several checks | score >= 90, age > 18 && hasTicket |
switch | One value is compared with many exact values, especially if some cases share code or run several lines | Order status, menu choice, day of the week |
| Object lookup | Each value simply maps to another value | Country code to country name |
A switch can't easily check ranges like score >= 90, so for a grade calculator, if/else is better.
When each case only gives back a value, an object lookup is often the shortest and cleanest choice. You'll learn objects properly later in the course; for now, think of an object as a dictionary where you look up a word (the key) and get its meaning (the value).
const countryCode = 'FR';
const countryNames = {
US: 'United States',
FR: 'France',
JP: 'Japan',
BR: 'Brazil'
};
const country = countryNames[countryCode] ?? 'Unknown country';
console.log(country);
// Output: France
countryNames[countryCode] looks up the key 'FR' and gives 'France'. If the code isn't in the object, the result is undefined, and ?? replaces it with 'Unknown country', just like default in a switch. The same job with a switch would take about twelve lines.
Practice exercise
Write a switch for a simple restaurant menu. Create const choice = 2;. Case 1 logs "You ordered a pizza.", case 2 logs "You ordered a salad.", case 3 logs "You ordered soup.", and default logs "Please choose 1, 2 or 3." Then add cases 4 and 5 that both log "Drinks are at the bar." using fall-through on purpose.
Hint: remember break after each case, and stack case 4: and case 5: with no code between them. Also remember that switch uses strict comparison, so the string '2' would not match case 2.
Key takeaways
- A switch compares one value against many cases using strict equality.
- Put
breakat the end of each case, or the code falls through to the next cases. defaultruns when no case matches.- Stacking cases with no code between them is a useful, intentional fall-through.
- Use if/else for ranges, switch for many exact values, and an object lookup when values simply map to other values.