javascript switch(true)

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.


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

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

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

Tags:

Javascript