Javascript triple statement result

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.

+6
source share
4 answers

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,

  • var a = k <100? o + = 2> 11? "T": "F": o <100? "J": "P";
  • var a = true ? o + = 2> 11? "T": "F": o <100? "J": "P";
  • var a = true ? o + = false ? "T": "F": o <100? "J": "P";
  • var a = true ? o + = "F" : o <100? "J": "P";
  • var a = true ? "78F" : o <100? "J": "P";
  • var a = "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 
+9
source
 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.

+3
source

You use += in o instead of + .

 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")); 
+1
source

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");

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

+1
source

All Articles