Javascript - Ternary Operator with Multiple Statements

Viewed 108759

Is this valid JavaScript? I saw an example where someone used commas in the ternary operator conditions, and it was marked as an error in my editor, and the example didn't run in Chrome. However, it did run in Firefox. Once I converted all the ternary statements to if/else statements, the app ran on Chrome.

a!==b ? (a=1, b=2) : (a=2, b=1)

Edit:

This is the actual statement in the code:

a!==0?b<0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0
5 Answers

Expanding on this topic with ES6 code example. If you're using one side of the TRUE : FALSE argument to iterate thru all cases in one IF, it makes sense to separate the code as if it's a switch | case statement.

Nesting implies that there is branching logic, while it is logically nested, writing nested IF's complicates what we're doing in my example. Like a lawyer over explaining a problem to a jury. IMO, you want to explain the point in it's simplest form. For instance, I find this example the most logical way of expressing nested ifs where the TRUE is executed. The final false is your last else {} choreDoor is either 0,1 or 2:

choreDoor === 0 ? 
   (openDoor1 = botDoorPath,
    openDoor2 = beachDoorPath,
    openDoor3 = spaceDoorPath)
: choreDoor === 1 ? 
   (openDoor2 = botDoorPath,
    openDoor1 = beachDoorPath, 
    openDoor3 = spaceDoorPath) 
: choreDoor === 2 ?
   (openDoor3 = botDoorPath,
    openDoor1 = beachDoorPath, 
    openDoor2 = spaceDoorPath)
: false;

If you don't want to use the Comma operator (,) then you can use nested Conditional (ternary) operators instead.

var a = 6;
var b = 7;
var c = (a !== b)?  // true
        ((a = 1 || 1===1)? (b = 2) : null) // will first run a=1, then b=2
      : ((a = 0 || 1===1)? (b = 0) : null);

console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);

Related