0

I have this block of switch statements, which the control variable has type string. I compared the value of this variable with another string in an if statement, it works. But it doesn't work if I put it in a switch statement.

The code is below:

type = $('serType');
    if (type == "Age"){
        logger.info('Age'.toLowerCase());
    }
    switch (type){
        case "TV":
            columnHeader = "";
            break;
        case 'Age':
        logger.info("i am in age case");
            columnHeader = "'id', 'pat_name', 'pat_age' ";
            break;              
        default:
        logger.info("i am in default case");
            break;
    }
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Trung Bún
  • 1,117
  • 5
  • 22
  • 47

1 Answers1

0

You're calling toLowerCase() in your case statement, converting "Age" to "age":

case 'Age'.toLowerCase()

Whereas in your if statement you are not doing this:

if (type == "Age")

"Age" and "age" are not the same thing. To fix this, remove the .toLowerCase() from your case statement:

case 'Age'

If you want to be able to catch both "Age" and "age", see this question: JavaScript case insensitive string comparison.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Sorry I that toLowerCase function is a mistake. It doesn't work even I remove the function. I wanted to test whether it works with lower case or not. Could you try to find the problem in my code again? – Trung Bún Aug 11 '15 at 15:40
  • @TrungBún are you getting any JavaScript errors? Is `logger` defined? – James Donnelly Aug 11 '15 at 15:42
  • It's all defined. I tried to print every single variable and they aren't null or empty. As you can see from the code above, the if statement works, but the switch statement doesn't .. – Trung Bún Aug 11 '15 at 15:44
  • @TrungBún there must be a different problem. Your JavaScript code works as is: http://jsfiddle.net/8tuLcq5q/ – James Donnelly Aug 11 '15 at 15:45
  • Is there any way that I can check type of variable in JavaScript? After auto wraping? Maybe the variable type is char or any other datatype. Sorry my JavaScript skill is weak.. – Trung Bún Aug 11 '15 at 16:04
  • @TrungBún char doesn't exist in JavaScript. You can use `typeof` to check its type: `if (typeof "Age" == "string")`. – James Donnelly Aug 12 '15 at 08:05