Needing some help with Multiple Identical Options in Switch Statements

Needing some help with Multiple Identical Options in Switch Statements
0

#1

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?


#2

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.


#3

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.


#4

Thought it would not pass the FCC tests, because they are expecting you to use 9 case statements, the following would work similar to what you were trying to do:

function sequentialSizes(val) {
  var answer = "";
  // Only change code below this line
  switch(true) {
    case val >= 1 && val <= 3:
      answer = "Low";
      break;
    case val >= 4 && val <= 6:
      answer = "Mid";
      break;
    case val >= 7 && val <= 9:
      answer = "High";
      break; 
  }
  
  // Only change code above this line  
  return answer;  
}