Enea Xharja Logo

The switch statement

switch

Selecting from Many Options with Switch Statements

The if/else statement is very useful to deal with more than two options. However, when we have many options to choose from, a switch statement is the ideal solution.

Example:

js
1function caseInSwitch(x) {
2 var answer = '';
3
4 switch (x) {
5 case 1:
6 return (answer = 'alpha');
7 break;
8 case 2:
9 return (answer = 'beta');
10 break;
11 case 3:
12 return (answer = 'gamma');
13 break;
14 case 4:
15 return (answer = 'delta');
16 break;
17 }
18
19 return answer;
20}
21
22caseInSwitch(1);

The value of x is checked for a strict equality (===) to the value from the first case (1), then to the second (2) and so on. If the equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break (or until the end of switch). If no case is matched then the default code is executed (if it exists).

In a switch statement, if we have many cases to deal with and we cannot specify all of them, we can add a default statement. This statement will be executed only if no matching case statements are found.

We can think of default as the final else statement in an if/else scenario, since both the statements are the last case.

Multiple Identical Options in Switch Statements

If we omit the break statement from a switch statement's case, the cases will execute until a break is encountered.

This can be a handy solution if we have multiple identical options that we might prefer to group together.

Example:

js
1function sequentialSizes(val) {
2 var answer = '';
3
4 switch (val) {
5 case 1:
6 case 2:
7 case 3:
8 answer = 'Low';
9 break;
10 case 4:
11 case 5:
12 case 6:
13 answer = 'Mid';
14 break;
15 case 7:
16 case 8:
17 case 9:
18 answer = 'High';
19 break;
20 }
21
22 return answer;
23}
24
25sequentialSizes(1);