Reputation: 131
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.
Upvotes: 2
Views: 44
Reputation: 386883
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
Upvotes: 1
Reputation: 68685
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
Upvotes: 2