4

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?

Comments
  • 19
    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.
  • 7
    It 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.
  • 3
    Ahh okay guys, thanks for clearing that up, I just assumed everything is evaluated before the in the Boolean expression before the ==
  • 4
    Stop trying to be smart and write a full expression.

    a === null || b === null
  • 4
  • 1
    @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.
  • 1
    @C0D4 Thanks for the useful article :)
  • 2
    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
  • 1
    @kamen Using == null is indeed very smart because he will then also catch undefines.
  • 2
    @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) { /* ... */ }
  • 2
    I see nothing wrong here
Add Comment