Needing some help with Multiple Identical Options in Switch Statements

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";

And I have to do this?:

switch (val) {
     case (1):
     case (2):
     case (3):
       answer= "Low";

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';

  case val <= 6:
    answer = 'Mid';
  // ...

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.

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";
    case val >= 4 && val <= 6:
      answer = "Mid";
    case val >= 7 && val <= 9:
      answer = "High";
  // Only change code above this line  
  return answer;