0

I have a switch statement which has several cases. These cases compare values and assign a text to a variable. But when I try to execute this switch, it always executes the default case. But my condition is true.. Why?

Here is my value

Apartment

Here is my code

var rental_cat = $('#rentals_type').val();
alert(rental_cat);
var rental_type = "";
switch (rental_cat) {
case (rental_cat == "Apartment"): 
    rental_type='daily';
    alert(rental_type);
    break;
case (rental_cat == "Office"):
    rental_type='work_daily';
    alert(rental_type);
    break;
default:
    rental_type='other';
    alert(rental_type);
    break;
}

When I execute this switch, it always gives me "other"

1

3 Answers 3

3

Remove the conditional expression inside the "case" clause.

Try this:

var rental_cat = $('#rentals_type').val();

    alert(rental_cat);

    var rental_type = "";

    switch (rental_cat) {

    case "Apartment": 
                                        rental_type='daily';
                                        alert(rental_type);
                                        break;

    case "Office":
                                        rental_type='work_daily';
                                        alert(rental_type);
                                        break;

    default:
                                        rental_type='other';
                                        alert(rental_type);
                                        break;
}
Sign up to request clarification or add additional context in comments.

3 Comments

@AshishVyas maybe you need to trim() the input?
Hi @AshishVyas, it's working for me. You can check here jsfiddle.net/pablodarde/wg1wdcd7
Thanks a lot @Thomas. after trim() that result, it works :)
0
switch (rental_cat) {
  case (rental_cat == "Apartment"): 

is equivalent to

switch (rental_cat) {
  case true: 

which in turn is equivalent to

if (rental_cat === true)

You don't put a condition in the case, the condition is created as an equality check between the switch and the cases, so it should be like this instead:

switch (rental_cat) {
  case "Apartment":

Comments

0

a switch is not the right structure to deal with this problem. Here I'd recommend a map:

var rentalTypesByCat = {
    DEFAULT:        "other",

    "Apartement":   "daily",
    "Office":       "work_daily",
}

var rental_cat = $('#rentals_type').val();
console.log("rental_cat:", rental_cat);

var rental_type = rentalTypesByCat[rental_cat] || rentalTypesByCat.DEFAULT;
console.log("rental_type:", rental_type);

or if you need it a bit more explicit (for example because some of your mapped values may be falsy themselves):

var rental_type = rentalTypesByCat[rental_cat in rentalTypesByCat? rental_cat: "DEFAULT"];
console.log("rental_type:", rental_type);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.