Use the switch
statement to select one of many code blocks to be executed.
Example 1
1// Find the current day
2switch (new Date().getDay()) {
3 case 1:
4 text = "Monday";
5 break;
6 case 2:
7 text = "Tuesday";
8 break;
9 case 3:
10 text = "Wednesday";
11 break;
12 case 4:
13 text = "Thursday";
14 break;
15 case 5:
16 text = "Friday";
17 break;
18 default:
19 text = "its weekend";
20 break;
21}
Output: Wednesday
Example 2
1// commond code blocks
2const x = 5;
3switch (x) {
4 case 6:
5 case 0:
6 text = "its weekend!";
7 break;
8 case 1:
9 case 2:
10 case 3:
11 case 4:
12 text = "First four days of weekdays!";
13 break;
14 default:
15 text = "its Friday!";
16 break;
17}
Output: its Friday!