Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Operator precedence plus lazy eval.
"a || b == null" stops evaluating after a because a is already something true-ish. Hence, 5. The operator precedence makes it equivalent to "a || (b == null)" I guess.
(a || b) gives 5 for the same reason (lazy eval), and 5 isn't null. -
p100sch15004yIt is straight forward even if it is counter intuitive. The comparison has higher priority than the boolean operator. Then the boolean operator returns the first non falsy value or false. When wrapped in brackets the operator precedence is overridden and the first truthy value is compared to null.
-
Ahh okay guys, thanks for clearing that up, I just assumed everything is evaluated before the in the Boolean expression before the ==
-
@kamen Well yeah, I did do that at first but I realised that it would probably return false if it's a null value so I tried to shorten it, was just trying to shorten the code.
-
I think this would happen in any language? || takes precedence over a comparison operator so you’re asking it execute a OR if a is false execute b == null
-
theuser48024y@kamen Using == null is indeed very smart because he will then also catch undefines.
-
kamen69954y@theuser Sure, but I personally prefer strict comparisons when I can use them. A good compromise is I think just checking for falsiness, e.g. if (!expression) { /* ... */ }
Just when I thought I understood boolean expressions in JavaScript.. this pops up... I've heard JavaScript's boolean's expressions was messed up -- but these should be equal.. surely?
rant
what
javascript
boolean expressions
boolean