In JavaScript, the switch statement provides a way to execute different blocks of code based on the value of an expression. It's an alternative to using multiple if , else if , and else statements when you have multiple conditions to check against a single value. Here's how the switch statement works:
switch (expression) {
case value1:
// Code block to execute if expression equals value1
break;
case value2:
// Code block to execute if expression equals value2
break;
case value3:
// Code block to execute if expression equals value3
break;
default:
// Code block to execute if expression does not match any case
}
let day = new Date().getDay();
let dayOfWeek;
switch (day) {
case 0:
dayOfWeek = "Sunday";
break;
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
case 6:
dayOfWeek = "Saturday";
break;
default:
dayOfWeek = "Invalid day";
}
console.log("Today is " + dayOfWeek);
You can group multiple cases together to execute the same code block for different values.
let month = new Date().getMonth();
let season;
switch (month) {
case 11:
case 0:
case 1:
season = "Winter";
break;
case 2:
case 3:
case 4:
season = "Spring";
break;
case 5:
case 6:
case 7:
season = "Summer";
break;
case 8:
case 9:
case 10:
season = "Autumn";
break;
default:
season = "Invalid month";
}
console.log("The current season is " + season);
The switch statement provides a concise way to handle multiple conditions based on the value of an expression. It's particularly useful when you have a large number of conditions to evaluate.