0

I dont understand why my function doesnt take the value 70.

let test = (age) => {
  switch (age) {
    case (age > 65):
      console.log("High age")
      break
    default:
      console.log("Low age")
      break
  }
}

test(70)
  • 2
    That's simply not how switch statements work. `age > 65` is evaluated to either `true` or `false`, neither of which is equal to `age` itself. You _could_ do `switch (age > 65)` then make the cases the booleans, but as below just _use a regular condition_. – jonrsharpe May 02 '23 at 22:05
  • Does this answer your question? [Switch statement for greater-than/less-than](https://stackoverflow.com/questions/6665997/switch-statement-for-greater-than-less-than) – pilchard May 02 '23 at 22:32
  • or [switch statement to compare values greater or less than a number](https://stackoverflow.com/questions/32576618/switch-statement-to-compare-values-greater-or-less-than-a-number) – pilchard May 02 '23 at 22:32

1 Answers1

0

To use a switch statement, you could modify your code like this:

let test = (age) => {
  switch (age) {
    case 65:
    case 66:
    case 67:
    case 68:
    case 69:
    case 70:
      console.log("High age");
      break;
    default:
      console.log("Low age");
      break;
  }
}

test(70);
DoBest
  • 1
  • 1
  • While this does switch on `age`, I would definitely recommend against this approach for obvious reasons. Just use the `>` operator (or similar) in e.g. an if-else statement. – Oskar Grosser May 02 '23 at 23:29