Reputation: 414
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.
Upvotes: 6
Views: 216
Reputation: 67217
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
Upvotes: 9
Reputation: 2516
This is actually working like
k < 100 ? o += (2 > 11 ? "T" : "F") : (o < 100 ? "J" : "P");
because anything on right side of assignment operator =
is processed first, in Left to Right order, so 2 > 11 ? "T" : "F"
is evaluated first
Upvotes: 1
Reputation: 712
var k = 27;
var o = 78;
var a = k < 100 ? (o+=2) > 11 ? "T" : "F" : o < 100 ? "J" : "P";
alert(a);
Above code works as expected by you.
You probably thought that the +=
operator would be processed first.
Upvotes: 3
Reputation: 1407
You are using +=
on o
instead of just +
.
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"));
Upvotes: 1