JavaScript switch Statement
JavaScript switch Statement
The switch statement is used for executing a block of code depending on different cases. It is part of JavaScript Conditional Statements which perform different actions under different conditions. It comes as a replacement for multiple if...else and nested if...else loops.
More Explanation:-
In the switch statement, an expression is evaluated. It is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed. It is used in combination with break and default keywords. They are optional but they are very important.
Break keyword:-
The break keyword breaks out of the switch block when a certain case match. Without it, the next code block in the switch statement is executed.
Default Keyword:-
The default keyword is used to specify some code to run if there is no case match. It is only used once in it.
Syntax:-
Its syntax is:-
switch(expression) {
case n:
//code block
break;
case n:
// code block
break;
default:
// default code block
}
Further Explanation:-
Parameter | Description |
---|---|
expression | Required. Specifies an expression to be evaluated. The expression is evaluated once and its value is matched with each case. If a match occur, then that block will be executed. |