Convert if statements into ternary conditional operators

Tags: ,



Apologize if it’s seems simple, I’m stack on this. I want to convert these if statements into ternary condition :

if a!='-' && b!='_'
action A
else
 if a=='-' action B else action C

I tried this and do not work for me, it only execute directly condition C

a!='-' && b!='_' ? Action A : (a=='-' ? Action B : Action C)

How to formulate that ? thanks.

Answer

Though with some magic letters it works. But please DON’T do it.

Nested terenary operations are harder to read and makes your Juniors cry. Don’t do it.

If you still want to do

(a!='-' && b!='_') ? Action A : (a=='-' ? Action B : Action C)

Example

    var a =1;
    var b=1;
    var c= 2;

    (a==1 && b==1) ? alert("AB: true") : ((c != 1) ? alert("C: true") : alert("false"))

Example 2 :

    var a =1;
    var b=1;
    var c= 2;

    (a==1 && b==2) ? alert("AB: true") : ((c != 1) ? alert("C: true") : alert("false"))


Source: stackoverflow