skip to Main Content

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

Answers


  1. If there’re only two options then simply use if-else statement:

    let test = (age) => {
      if (age > 65) {
        console.log("High age");
      } else {
        console.log("Low age");
      }
    }
    
    test(70); //High age
    

    BTW The problem with your code is that boolean expressions like (age > 65) are evaluated to be either true or false, neither of which is equal to age itself.

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search