javascript switch(true)

Hi i am trying to handle an ajax json response

here is my code

success: function (j) {     
    switch(true)
    {
        case (j.choice1):

            alert("choice2");
        break;
        case (j.choice2):
                alert("choice2");
        break;
        default:
            alert("default");
        break;
    }
}

based on what j is return i do my action BUT i keep getting the default.

I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.

I tried case (j.choice1!=””) (j.choice2!=””) But in this scenario i keep getting the first choice.

What am i missing

It works for me:

var a = 0, b = true;
    
switch(true) {
    case a:
        console.log('a');
        break;
    case b:
        console.log('b');
        break;
}

However, the case labels must be equal to true, not jut implicitly true.
Also, only the first case that evaluates to true will execute.

SOLVED

Based on SLaks answer i modify the code as below

    if(j.choice1){ var choice1=true;} else { var choice1=false;}
    if(j.choice2){ var choice2=true;} else { var choice2=false;}

    switch(true)
    {
        case choice1:
            alert("choice1");
        break;
        case choice2:
            alert("choice2");
        break;
        default:
            alert("default");
        break;
    }

For all asking why switch and not if.

Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).

The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute

Thank to all

You need to read up on the switch statement. You should not be switching on a constant value.

Read More:   Equivalent to LINQ's Enumerable.First(predicate)

It appears that you need to use if statements, as you don’t really want to be switching on your j value:

success: function (j) {     
    if (j.choice1)
    {
        alert("choice1");
        break;
    }

    if (j.choice2)
    {
        alert("choice2");
        break;
    }

    alert("default");
  }
}

In a case like this, a better way to do this is probably something like:

success: function (j) {
    if(j.choice1 || j.choice2) {
        alert("choice2");
    } else {
        alert("default");
    }
}

Why not use an object literal instead of a switch(true) ?

const j= {
    choice1: false,
    choice2: true
};

const map = {
    true: 'default',
    ...(j.choice1 ? {[`${j.choice1}`]: 'choice1'} :{}),
    ...(j.choice2 ? {[`${j.choice2}`]: 'choice2'} :{})
}['true']

console.log(map) // 'choice2'


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts