Javascript Switch
The switch statement is used to represent various actions based on different conditions. It can replace multiple if checks and gives a more descriptive way of comparing a value with multiple variants.
To perform a multiway branch, you can use multiple else…if statements, as in the previous chapter, but it is not the best way. It is better to use a switch statement which is more efficient than repeated else if statements.
Syntax
The main objective of a switch is to give an expression for evaluating and many various statements for executing. Both objectives are based on the value of the expression. The interpreter is checking each case against the value of the expression until it founds a match. If nothing matches, there will be used a default condition.
The switch statement has one or more case blocks and an optional default, which looks like this:
switch (x) {
case 'value1': // if (x === 'value1')
...[
break
]
case 'value2': // if (x === 'value2')
...[
break
]
default:
...[
break
]
}
- The value of x is checked for equality of a strict to the value from the first case, it is value2, then to the second value2, and so on.
- If the equality is found, switch executes the code starting from the analogous case, until the end of the switch.
- If nothing matched, the default code will be used.
The switch compares a from the 3 which is the first case variant, the match fails.
Then 6 that is a match, it means that the execution starts from case 6 until the nearest break.
If there is no break the execution will continue with the next case without any checks.
Example of the switch without break:
When JavaScript meets a break keyword, it breaks out of the switch block. That stops the execution of inside the block.
It is not important to break the last case in a switch block, the block breaks there anyway.
The default keyword defines the code to run if there is no case match.
The examples shows that +a gives 4, that’s compared with b * 2 in case, and the corresponding code is implemented.
Grouping of “case”
If several variants of case share the same code they can be grouped. So if we want the same code to run for case 2 and case 3 or case 5, case 6 and case 8 we do this:
let val;
let answer = "";
switch (val) {
case 1:
answer = "Low";
break;
case 2: // (**)
case 5:
answer = "Mid";
break;
case 3:
case 6:
case 8:
answer = "High";
break;
default:
answer = "Massive?";
}
At the result, both 2 and 5 cases and 3, 6, 8 cases show the same message.
The ability to “group” cases is an aftereffect of how switch/case works without break. The execution of case 2 starts from the line (**), then it goes through case 5 because there’s no break.
Type matters
Let’s focus attention on the equality check that is always strict. The values here must be of the same type to match.
0 Comments
CAN FEEDBACK
Emoji