Multiple Identical Options in Switch Statements:
For this lesson why can i not do this :
1-3 - “Low”
4-6 - “Mid”
7-9 - “High”
switch (val) {
case (val >=1, val <=3):
answer = "Low";
break;
And I have to do this?:
switch (val) {
case (1):
case (2):
case (3):
answer= "Low";
break;
I mean its the exact same thing, no?
No, they’re not the same. switch
does a strict comparison (i.e., using the ===
operator) between the test value (the variable after the switch
keyword) and the values after the case
keywords.
If val
is a number, then doing a strict comparison to compare it to a boolean (like val >= 1
) will always be false. So yeah, you have to spread the values with multiple case
keywords.
You can use relational operators in a switch
block:
switch (true) {
case val <= 3:
answer = 'Low';
break;
case val <= 6:
answer = 'Mid';
break;
// ...
}
I think this style is a matter of personal taste though.
1 Like
Yes you don’t need the parenthesis around the single numbers or conditionals. You only need them when you want an operation to be done before the conditional statement is applied.