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
1 2 3 4 5 6 7 8 9 10 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <!DOCTYPE html> <html> <body> <p id="day"></p> <script> showDay(); function showDay() { var dt = new Date(); var dtNo = dt.getDay(); switch (dtNo) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; } document.getElementById("day").innerHTML = day; } </script> </body> </html> |