The Default Clause
You'll learn how to handle unexpected or unmatched values in a switch statement using the default clause.
What It Does
The default clause in a switch statement acts as a catch-all for any value that doesn't match any of your explicit case labels. Think of it like an "everything else" bucket—when none of your cases match, the default code runs.
Analogy: Imagine a vending machine where you press buttons A1, A2, or A3. If someone presses an unlabeled button, the machine has a default response: "Invalid selection." That's what default does—it handles the unexpected.
Basic Syntax
let color = 'purple';
switch (color) {
case 'red':
console.log('Stop');
break;
case 'yellow':
console.log('Slow down');
break;
case 'green':
console.log('Go');
break;
default:
console.log('Unknown color');
}
// Logs: "Unknown color"
Since 'purple' doesn't match any case, the default block executes.
Placement and Best Practices
The default clause typically appears at the end of the switch statement, though technically it can go anywhere. Placing it last is conventional and easier to read.
let day = 10;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
console.log('Weekday');
break;
default:
console.log('Not a standard weekday number');
}
You don't need a break after default if it's the last clause, but adding one doesn't hurt and maintains consistency.
Key Takeaway: The default clause handles values that don't match any explicit case, preventing silent failures and making your code more robust.