Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ternary operator result

I am making small utility to compile javascript block using C#. I am trying to understand ternary operator's execution flow. Now when I am running a javascript using Chrome or Firefox :

var k = 27;
var o = 78;
var a = k < 100 ? o+=2 > 11 ? "T" : "F" : o < 100 ? "J" : "P";
alert(a);

It should have give me result "T" or "F" if "o+=2" returns false. But instead of those it returns "78F". Can anyone please explain me whats the logic behind it.

like image 308
Arnab Avatar asked Mar 11 '16 16:03

Arnab


1 Answers

Based on the operator precedence table:

Assignment operators has less priority than a comparison operator.

So your code will be evaluated like below,

  1. var a = k < 100 ? o+=2 > 11 ? "T" : "F" : o < 100 ? "J" : "P";
  2. var a = true ? o += 2 > 11 ? "T" : "F" : o < 100 ? "J" : "P";
  3. var a = true ? o += false ? "T" : "F" : o < 100 ? "J" : "P";
  4. var a = true ? o += "F" : o < 100 ? "J" : "P";
  5. var a = true ? "78F" : o < 100 ? "J" : "P";
  6. var a = "78F"

And you can correct the behaviour by grouping the condition using a parenthesis,

var a = (k < 100) ? (o+=2) > 11 ? "T" : "F" : (o < 100) ? "J" : "P";
console.log(a); // T
like image 116
Rajaprabhu Aravindasamy Avatar answered Oct 19 '22 22:10

Rajaprabhu Aravindasamy