Basic JavaScript - Multiple Identical Options in Switch Statements

Tell us what’s happening:
why ( , ) cant be used in this case?

Your code so far

switch (val){
case 1,2,3:
answer = “Low”;
break;
case 4,5,6:
answer = “Mid”;
break;
case 7,8,9:
answer = “High”;
break;
}

A case statement matches val against a single potential value.

In JavaScript, you cannot use commas (,) to specify multiple values for a single case statement. Instead, you need to write separate case statements for each value you want to match. Each case statement should have its own break statement or a block of code to execute.

For example, if you want to match values 1, 2, and 3, you would write it like this:

switch (val) {
  case 1:
  case 2:
  case 3:
    // Code to execute if val is 1, 2, or 3
    break;
  // Other cases...
}

This code will execute the same code block for val equal to 1, 2, or 3. Using separate case statements without a break statement for each value allows you to group them together and perform the same action for all of them.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.