In JavaScript, a switch case is a conditional statement that is used to provide a way to execute different blocks of code based on the value of an expression.
The switch statement is used to execute one block of code from multiple alternatives based on the value of an expression. It provides an alternative to multiple if else if statement when comparing a single value against several possible options.
Here is the syntax of using switch statement:
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to executed
break;
default:
//code to be executed if no case matches
}
Explanation:
expression: The value or variable that is evaluated once and compared with each case value.
case value1, case value2: These define the possible values that are compared with the expression. If a match is found, the corresponding code block is executed.
break: Terminates the current case and exits the switch statement. Without break, execution continues to the next case.
default: An optional block that executes when none of the case values match the expression. It works similarly to the else block in an if...else statement.
Top comments (0)