The switch statement performs different actions based on different condition.
It can be called as the replacement of multiple nested if-else statements.
The JavaScript Switch Statement
- The switch statement is used to select one of many code blocks to be executed.
- Switch case is useful for menu based application.
Syntax
switch(expression/variable) {
case a:
// code block
break;
case b:
// code block
break;
default:
// code block
}
How Switch Statement works?
- At first, the switch expression is evaluated once.
- The value of the expression is compared with each of the case.
- If there is a match, the associated block of code is executed i.e., only one case will be executed.
- If break is not written after each of the code blocks, all the cases are executed after execution of the matched case.
- The default portion is executed only when the user inputs a wrong value(other than the case values).
The getDay() method returns the weekday as a number within the range 0-6.
(Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6)
Example