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.
Based on the operator precedence table:
Assignment operators has less priority than a comparison operator.
So your code will be evaluated like below,
true
? o += 2 > 11 ? "T" : "F" : o < 100 ? "J" : "P"; true
? o += false
? "T" : "F" : o < 100 ? "J" : "P";true
? o += "F"
: o < 100 ? "J" : "P";true
? "78F"
: o < 100 ? "J" : "P";"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With