1

I am writing a switch statement in JavaScript and instead of giving an exact value as case value I use a comparison.

 switch (age) {
case age<18:
    alert("You are a child");
    break;
case age>18:
    alert("You are an adult");
    }

This code did not give any output and then I changed the expression within switch into true.

 switch (true) {
case age<18:
    alert("You are a child");
    break;
case age>18:
    alert("You are an adult");
    }

Could anybody please explain the reason why this code didn't work at the first attempt.

YUMI
  • 94
  • 9
  • I've never seem `switch(true)`, but I think it's a interesting way for pattern matching :) – apple apple Mar 31 '20 at 06:42
  • @appleapple You can also check this [answer](https://stackoverflow.com/a/12259830/1823841) for some more interesting way for pattern matching :) – palaѕн Mar 31 '20 at 06:48
  • @palaѕн thanks for the link, but the answer you linked, while looks like have many choice, most of them are hash/lookup (and are in fact not-that-related to switch). When I say pattern matching, I'm more interested in generalized switch like `switch(true){case foo instanceof Foo:dosomething();}` thanks for inform me anyway. – apple apple Mar 31 '20 at 07:00

2 Answers2

3

switch uses === to compare the switched expression against every case. For example, if age is 13, then

switch (age) {
  case age < 18:
    alert("You are a child");
    break;
  case age > 18:
    alert("You are an adult");
}

evaluates to

switch (13) {
  case 13 < 18:
    alert("You are a child");
    break;
  case 13 > 18:
    alert("You are an adult");
}

which is

switch (13) {
  case true:
    alert("You are a child");
    break;
  case false:
    alert("You are an adult");
}

The switched expression, 13, is not equal to any of the cases.

You need to logic your way through it - if, when using switch, your switched expression is not going to be === to any of the cases, use switch(true), which works if the cases are conditionally true:

switch (true) {
  case age < 18:
    alert("You are a child");
    break;
  case age > 18:
    alert("You are an adult");
}

when age is 13, evaluates to

switch (true) {
  case true:
    alert("You are a child");
    break;
  case false:
    alert("You are an adult");
}

Now, the switched expression true is === to one of the cases.

Or, even better, just use if/else, there are rarely any good times to use switch IMO:

if (age < 18) {
  console.log('You are a child');
} else {
  console.log('You are an adult');
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

What the Switch does is compare for equality between the value and the cases. So, in this case, it is comparing the age value (for example 10) to the value true of age < 18. So this would trigger the alert in the second example. But 18 !== true, and 18 !== false too, so this wouldn't trigger any alert.

Gerard
  • 196
  • 6