Arnab
Arnab

Reputation: 414

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.

Upvotes: 6

Views: 216

Answers (4)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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,

  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

Upvotes: 9

Ammar Hasan
Ammar Hasan

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

RhinoDevel
RhinoDevel

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

Matt
Matt

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

Related Questions