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");

}

1
  • This is a duplicate: 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. Commented Jun 18, 2015 at 20:36

4 Answers 4

4

Just lower case it initially.

var grade = prompt("Please enter your class").toLowerCase() ;
Sign up to request clarification or add additional context in comments.

Comments

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");
}

Comments

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
}

Comments

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");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.