JavaScript Switch
JavaScript switch Statement
Section titled “JavaScript switch Statement”The switch statement is a control flow statement used to execute different blocks of code based on the value of an expression. It’s often an alternative to a long if...else if...else chain when dealing with multiple discrete values.
Understanding the switch Statement
Section titled “Understanding the switch Statement”The switch statement evaluates an expression once and compares its value against a series of case clauses. If a match is found, the code block associated with that case is executed.
Syntax:
Section titled “Syntax:”switch (expression) { case value1: // Code block to execute if expression === value1 break; // Important: stops execution from falling through case value2: // Code block to execute if expression === value2 break; // ... more cases default: // Code block to execute if no case matches // (optional, but good practice)}How it works:
- The
expressionis evaluated once. - The value of the
expressionis compared with the value in eachcaseusing strict equality (===). - If a match is found, the code block starting from that
caseis executed. - The
breakkeyword is crucial. If omitted, execution will “fall through” to the nextcaseblock, regardless of whether its value matches. This can be intentional but is often a source of bugs if unintended. - The
defaultclause is optional. It executes if nocasematches the expression’s value. It’s good practice to include adefaultcase, even if it’s just for logging an unexpected value.
Example: Getting the day of the week.
let dayName;const dayNumber = new Date().getDay(); // 0 for Sunday, 1 for Monday, ..., 6 for Saturday
switch (dayNumber) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; default: dayName = "Invalid day number"; // Should not happen with getDay()}
console.log(`Today is ${dayName}.`);The break Keyword
Section titled “The break Keyword”When the JavaScript interpreter reaches a break keyword inside a switch block, it exits the switch statement entirely. Execution continues with the statement immediately following the switch block.
If break is omitted, execution continues into the next case block. This is called “fall-through” and can sometimes be used intentionally, but it’s a common source of errors if forgotten.
Example of fall-through (intentional):
const fruit = "apple";let type;
switch (fruit) { case "apple": case "pear": case "banana": type = "Common fruit"; break; // Exits switch here case "orange": case "lemon": type = "Citrus fruit"; break; default: type = "Unknown fruit";}console.log(`${fruit} is a ${type}.`); // Output: apple is a Common fruit.The default Keyword
Section titled “The default Keyword”The default keyword specifies the block of code to run if no case value matches the switch expression. It’s similar to the else clause in an if...else statement.
The default case does not have to be the last case in a switch block. However, if it’s not the last, it must end with a break statement to prevent fall-through into subsequent case blocks.
Example with default:
const userRole = "guest";let permissions;
switch (userRole) { case "admin": permissions = "Full access"; break; case "editor": permissions = "Can write and edit content"; break; default: permissions = "Limited access or view only"; // No break needed if it's the last clause}
console.log(`Role: ${userRole}, Permissions: ${permissions}`);Strict Comparison
Section titled “Strict Comparison”It’s important to remember that switch uses strict comparison (===). This means the type and value of the expression must match the type and value of the case.
const value = "5";
switch (value) { case 5: // This is a number, value is a string "5" console.log("Matched number 5"); break; case "5": // This is a string, matches value console.log("Matched string '5'"); break; default: console.log("No match");}// Output: Matched string '5'Alternative to switch for Simple Lookups
Section titled “Alternative to switch for Simple Lookups”For simple value-to-value mappings, an object literal or a Map can sometimes be a cleaner alternative to a switch statement, especially if there’s no complex logic or fall-through involved.
// Using an object literal for lookupconst fruitColors = { apple: "red or green", banana: "yellow", orange: "orange"};
const selectedFruit = "banana";const color = fruitColors[selectedFruit] || "unknown color";console.log(`The color of ${selectedFruit} is ${color}.`);However, switch remains useful when actions beyond simple value assignment are needed for each case, or when fall-through logic is intentionally used.
For more details and examples, refer to the MDN documentation on switch.