I am making a small utility to compile a javascript block using C #. I am trying to understand the flow of ternary operator execution. Now when I run 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 given me the result of "T" or "F" if "o + = 2" returns false. But instead, he returns "78F" . Can someone please explain to me what the logic behind this is.
Based on the operator's priority table :
Assignment operators have lower priority than the comparison operator.
So, your code will be evaluated as shown below,
true
false
"F"
"78F"
And you can fix the behavior by grouping the condition using parentheses,
var a = (k < 100) ? (o+=2) > 11 ? "T" : "F" : (o < 100) ? "J" : "P"; console.log(a); // T
var k = 27; var o = 78; var a = k < 100 ? (o+=2) > 11 ? "T" : "F" : o < 100 ? "J" : "P"; alert(a);
The above code works as expected. You probably thought that the += operator would be processed first.
+=
You use += in o instead of + .
o
+
var a = k < 100 ? o+2 > 11 ? "T" : "F" : o < 100 ? "J" : "P";
Also, using parentheses will make it more readable:
var a = (k < 100 ? (o+2 > 11 ? "T" : "F") : (o < 100 ? "J" : "P"));
Does it really work like k < 100 ? o += (2 > 11 ? "T" : "F") : (o < 100 ? "J" : "P"); k < 100 ? o += (2 > 11 ? "T" : "F") : (o < 100 ? "J" : "P");
k < 100 ? o += (2 > 11 ? "T" : "F") : (o < 100 ? "J" : "P");
because first something is processed on the right side of the assignment operator = , in order from left to right, so 2 > 11 ? "T" : "F" 2 > 11 ? "T" : "F" is rated first
=
2 > 11 ? "T" : "F"