Home > database >  JS switch case not working with numbers when also using types and strings
JS switch case not working with numbers when also using types and strings

Time:04-09

I have a small problem. I have a parameter variable that can be either a type like undefined or a number. However when i try to check for a number it won't work. Why?

let parameters = 2

      // returns number
      console.log(typeof parameters)
      
      // returns 2
      console.log(parameters)

      switch (parameters) {
        case undefined:
          res.send(users).status(200);
          break;
        case "download":
          // creates file for all users
          handler.createAndSendFile("users", "csv", users, res);
          break;
        case parameters === 'number':
          console.log("Number getById 1");
          break;
        case (typeof parameters === 'number'):
          console.log("Number getById 2");
          break;
        case (parameters instanceof Number):
          console.log("Number getById 3");
          break;
        case (!isNaN(parameters)):
          console.log("Number getById 4");
          break;
        case parameters > 0:
          console.log("Number getById 4");
          break;
        default:
              console.log("default")
      }

CodePudding user response:

You are comparing parameters with other cases values, in the following cases:

  • parameters === undefined
  • parameters === "donwload"
  • parameters === (parameters === 'number') // witch is 'true'
  • parameters === (typeof parameters === 'number')
  • ...

If you want to evaluate a operation, you can do like:

let parameters = 2;

switch (true) {
  case !parameters:
    res.send(users).status(200);
    break;
  case parameters === "download":
    handler.createAndSendFile("users", "csv", users, res);
    break;
  case typeof parameters === 'number':
    console.log("Number getById 2");
    break;
}
  • Related