In JavaScript, the switch
statement is a control structure that allows different actions to be performed based on the different values of a variable. This structure helps avoid using multiple if-else
statements, making the code cleaner and more readable. Here’s how the switch
statement works in JavaScript, along with examples:
switch(expression) {
case value1:
// Actions for value1
break;
case value2:
// Actions for value2
break;
...
default:
// Actions if no match is found with any case
}
- expression: The variable or expression being evaluated.
- case value: One of the values to compare the expression against.
- break: A keyword used at the end of each case to exit the
switch
statement. - default: Specifies the actions to take if no
case
matches the expression.
Example Usage
let day = new Date().getDay();
let dayName;
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";
break;
default:
dayName = "Unknown";
}
console.log("Today is: " + dayName);
In the above example, the switch
statement checks the value of the day
variable based on the day of the week, and assigns the corresponding day name to the dayName
variable.
Things to Keep in Mind
- The
break
keyword should be used at the end of each case statement; otherwise, theswitch
statement will fall through to the next case. - The
default
case should always be written last. - The values in the expression should be constants. If checking variables or expressions, other methods should be used.
In JavaScript, the switch
statement is an effective way to set up decision-making logic for specific values. Using switch
instead of conditional statements for user inputs or other conditions makes the code more organized and understandable.