2

I have problem with a variable I made (it's a string) in JavaScript. It will be prompt from the user and then with the switch I will check if it is true or not. Then when I input it upper case it will say it is identified as a another var.

Here is my code:

var grade = prompt("Please enter your class") ;

switch ( grade ){
    
    case "firstclass" :
         alert("It's 500 $")
         break;
    case "economic" :
         alert("It's 250 $")
         break;
    default:
         alert("Sorry we dont have it right now");

}
Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
  • This is a duplicate: http://stackoverflow.com/q/2140627/830125. Those who have posted or might post answers: please do not answer questions that are blatant duplicates, despite the easy rep gain. Flag as a duplicate instead. – Drew Gaynor Jun 18 '15 at 20:36

4 Answers4

4

Just lower case it initially.

var grade = prompt("Please enter your class").toLowerCase() ;
nicael
  • 18,550
  • 13
  • 57
  • 90
3

as @nicael stated just lowercase what they input. However, if you need to preserve the way it was input and only compare using the lowercase equivalent, use this:

var grade = prompt("Please enter your class") ;

switch ( grade.toLowerCase() ){

  case "firstclass" :
     alert("It's $500");
     break;
  case "economic" :
     alert("It's $250");
     break;
  default :
     alert("Sorry we don't have it right now");
}
iam-decoder
  • 2,554
  • 1
  • 13
  • 28
0

You could set the entire string to lower case by using the String prototype method toLowerCase() and compare the two that way.

To keep the input the same, mutate the string during your switch statement:

switch( grade.toLowerCase() ) {
  // your logic here
}
Richard Kho
  • 5,086
  • 4
  • 21
  • 35
0

You should always compare uppercase string with uppercase values in case sensitive languages.
Or lower with lower.

var grade = prompt("Please enter your class") ;

switch (grade.toUpperCase())
{    
case "FIRSTCLASS" :
     alert("It's 500 $")
     break;
case "ECONOMIC" :
     alert("It's 250 $")
     break        ;
default   :
     alert("Sorry we dont have it right now");
}
King Clauber
  • 39
  • 10