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”;
case 4,5,6:
answer = “Mid”;
case 7,8,9:
answer = “High”;

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
  // 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