2

Can someone explain what will be the order of execution of following JavaScript Code:

(true + false) > 2 + true

I understand using + operator over two Boolean values returns the result as 0,1 or 2 depending upon the values being provided.

I interpreted output of above code as 1 by breaking the execution in following order:

1) (true + false) // Outputs : 1
2) 1 > 2 // Outputs : false
3) false + true //Outputs : 1

But the actual result is:

false

Can anyone correct my understanding if am interpreting the code in wrong way.

0

2 Answers 2

2

Your 2nd point is not correct.

1) (true + false) outputs - 1
2) (2 + true) - outputs 3
3) 1 > 3 - outputs false

You can check this using functions

(true + false) > 2 + true

function f1() {
  const cond = true + false;
  console.log(cond);
  return cond;
}

function f2() {
  const cond = 2 + true;
  console.log(cond);
  return cond;
}

console.log(f1() > f2());

If you want to compare with 2 then add true, you must to wrap into the parentheses

((true + false) > 2) + true
Sign up to request clarification or add additional context in comments.

2 Comments

So you mean first both + operator will be executed then comparison will take place?
Yes, for the first example. The second will work inside parentheses than + true
1

What you have is a question of operator precedence, of three parts,

  • ( ... ) grouping with the highest precedence of 20,

  • + adition with precedence of 13, and

  • > greater than (here) with the lowest precendece of 11.

That means the operators with higer precedence are evaluated first and the comes the once with lower precedence.

(true + false) > 2 + true
(true + false)             -> 1
                 2 + true  -> 3

             1 > 3         -> false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.