Why parenthesis don't change the operator priority for == and === in JavaScript?
I'm kind of confused! Why paranthesis don't affect the priority in these statements?
true === '0' ==开发者_Go百科 0 // returns true
(true === '0') == 0 // returns true again!
because true === '0'
evaluates to false
, and false == 0
is true. (because false
and 0 are both "non-truthy")
Remember that ===
compares strict equality and ==
tests for equality with conversion.
It's not that the priority is different, it's that both groupings evaluate to true:
true === '0'
is false
false == 0
is true
'0' == 0
is true
true === true
is true
You might want to review the JS truth table
Because (true === '0')
is false and false == 0
is true in both cases.
In other words:
(true === '0') == 0
resolves to
false == 0
Which is true.
Because the operators ===
and ==
have the same precedence are are left-to-right associative. Both the expressions result in the same interpretation. Consider the following expressions as for why the result is what it is:
true === '0' // false
// so: true === '0' == 0 is false == 0 and;
// (true === '0') == 0 is (false) == 0 is false == 0 and;
false == 0 // true
Happy coding.
> true === '0'
false
> false == 0
true
(true === '0') == 0
This one evaluates to:
false == 0 // which is true
Because (true === '0') is false and false == 0 is true and in this case JavaScript is nt doing a strict type comparison if you want it to return false change second part to ===
because true === '0' return false and false == 0 return true
Even with the paranthesis, your first check will always return false and
false == 0 will always return true
The === will check if the value is exactly the same (type inculded). So since you compare a char with a boolean, the result will alway be false.
By using parenthesis, you have not changed the order of execution. It was left to right even without parenthesis. The left part true=='0' returns 0.
0 == 0 returns true, so final answer is true both the times.
精彩评论