Multiple Cases Sharing Code
What you'll learn: How to make several case labels execute the same code block in a switch statement.
The Core Idea
Sometimes different values should trigger the exact same behavior. Instead of duplicating code for each case, JavaScript lets you stack multiple case labels on top of each other with no code between them. This leverages the fall-through behavior you just learned—but in a controlled, intentional way.
How It Works
When you list several case labels consecutively without any code or break statements between them, they all "fall through" to the first shared code block:
let day = 'Saturday';
switch (day) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
console.log('It is a weekday');
break;
case 'Saturday':
case 'Sunday':
console.log('It is the weekend!');
break;
}
// Output: "It is the weekend!"
All five weekday cases share one code block, and both weekend cases share another. This keeps your code DRY (Don't Repeat Yourself).
Think of It Like a Sorting Hat
Imagine a sorting system that drops items into bins. Multiple labels point to the same bin—whether you scan "apple," "banana," or "orange," they all drop into the "fruit" bin. Same concept: different inputs, same action.
Practical Example
let grade = 'B';
switch (grade) {
case 'A':
case 'B':
console.log('Great job!');
break;
case 'C':
console.log('Good effort');
break;
case 'D':
case 'F':
console.log('Needs improvement');
break;
}
// Output: "Great job!"
Key Takeaway: Stack multiple case labels together without code between them to execute the same block for different values, making your switch statements cleaner and more maintainable.