Inequalities inside a switch statement

2.7k Views Asked by At

I just started learning about the switch command in JavaScript, and was wondering if the cases could be constructed so as to include inequalities (<, >, <= and >=), instead of equality (==). Also, can one control whether it is a strict equality (===) or not? The following code does not even bring up a prompt, so I'm not sure if I've coded correctly:

var a = prompt("Please input a number.");

switch (a) {
  case { < 1 }:
    alert("less than 1");
    break;
  case { < 2 }:
    alert("less than 2");
    break;
  case { < 3 }:
    alert("less than 3");
    break;
  default:
    alert("greater than or equal to 3");
}

1

There are 1 best solutions below

2
On BEST ANSWER

It is actually possible, if you do it like this. The case whose expression evaluates to true is executed.

var a = +prompt("Please input a number.");

switch (true) {
    case (a<1): alert("less than 1"); 
    break;
    case (a<2): alert("less than 2");
    break;
    case (a<3): alert("less than 3");
    break;
    default: alert("greater than or equal to 3");
}

Note: Personally I feel you should use if-else for this purpose.