The switch
statement evaluates an expression, matching the expression's value to a case
clause, and executes statements associated with that case. It provides a more readable alternative to a long series of if-else if
statements when you have multiple, distinct values to check against a single variable.
Example 1: Basic Switch Statement
// Get the current day of the week as a number (0-6)
let day = new Date().getDay();
let dayName;
// Switch statement to find the name of the day
switch (day) {
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";
}
console.log(`Today is ${dayName}.`);
Explanation: This code gets the current day of the week as a number. The switch
statement then matches this number to a corresponding case
and assigns the correct day name to the dayName
variable.
Example 2: Switch with a Default Case
// Define a variable representing a user's subscription level
let userLevel = "gold";
let userPermissions;
// Switch statement to assign permissions based on subscription level
switch (userLevel) {
case "admin":
userPermissions = "Full Access";
break;
case "premium":
userPermissions = "Access to premium content";
break;
case "member":
userPermissions = "Access to member-only articles";
break;
default:
userPermissions = "Guest Access"; // This runs if no other case matches
}
console.log(`Your permission level is: ${userPermissions}`);
Explanation: The default
case in this switch
statement acts as a catch-all. If the userLevel
variable does not match any of the specified cases ('admin', 'premium', or 'member'), the default
block is executed.
Example 3: Grouping Cases (Fall-through)
// Define a variable for a character grade
let grade = 'B';
let feedback;
// Switch statement to provide feedback based on the grade
switch (grade) {
case 'A':
feedback = "Excellent!";
break;
case 'B':
case 'C':
feedback = "Good job, you passed."; // Cases 'B' and 'C' share this feedback
break;
case 'D':
feedback = "You can do better.";
break;
default:
feedback = "You failed.";
}
console.log(feedback);
Explanation: This example demonstrates how to group multiple cases. Since there is no break
statement after case 'B'
, the code "falls through" and executes the code for case 'C'
.
Example 4: Importance of the 'break' Statement
// Define a variable for a product code
let productCode = 1;
// Switch statement to display product information
switch (productCode) {
case 1:
console.log("Product: Laptop");
// Without 'break', it would continue to the next case
case 2:
console.log("Product: Keyboard");
break; // Stops execution here
case 3:
console.log("Product: Mouse");
break;
}
Explanation: If the break
statement were omitted from case 1
, the code would execute the console.log
for "Product: Laptop" and then continue to execute the code for case 2
, logging "Product: Keyboard" as well. The break
keyword is essential for separating the logic of each case.
Example 5: Using Strings in Cases
// Define a variable for a browser name
let browser = "Chrome";
let compatibility;
// Switch statement to check browser compatibility
switch (browser) {
case "Chrome":
case "Firefox":
case "Edge":
compatibility = "Fully supported.";
break;
case "Safari":
compatibility = "Partially supported.";
break;
default:
compatibility = "Not supported.";
}
console.log(`Browser compatibility: ${compatibility}`);
Explanation: This demonstrates that case
clauses are not limited to numbers. Here, we are using string values to check the name of a web browser and determine its compatibility level.
Example 6: Switch Inside a Function
// Function to get the name of a season based on the month number
function getSeason(month) {
let season;
// Switch statement to determine the season
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid Month";
}
return season;
}
console.log(`The current season is ${getSeason(4)}.`); // Outputs: The current season is Spring.
Explanation: This example encapsulates a switch
statement within a function. The function takes a month number as an argument and returns the corresponding season, making the logic reusable.
Example 7: Switch with Expressions in Cases
// Define a variable for a numeric value
let value = 15;
let result;
// Switch statement with boolean expressions in cases
switch (true) {
case (value >= 0 && value <= 10):
result = "Value is between 0 and 10";
break;
case (value > 10 && value <= 20):
result = "Value is between 11 and 20";
break;
default:
result = "Value is outside the defined ranges";
}
console.log(result);
Explanation: This less common but powerful pattern uses switch(true)
. Each case
is an expression that evaluates to either true
or false
. The first case
that evaluates to true
is executed.