4

As the title said, I can't quite understand why (true && {}) gives me {}, but the reverse is not the same.

Edit: As a followup, since I'm using a boolean operator, why does this expression not give me a boolean when evaluated?

william.taylor.09
  • 2,145
  • 10
  • 17
  • The JavaScript `&&` and `||` operators do not give boolean values. They're different from the similar operators in Java and C etc. They return the value of one or the other of their operands. – Pointy Apr 29 '15 at 21:10

3 Answers3

12

The expression operands to && are evaluated left to right. The value of the && expression is the value of the subexpression last evaluated. In your case, that'll be the right-most expression in both cases.

So, with (true && {}), the && operator first evaluates true. It's not falsy, so it then evaluates {} and returns that expression result.

With ({} && true) it does the same things backwards, so the second expression evaluated is true.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

a && bwill return a if a is falsy, otherwise b.

Indeed, if a is falsy (such as '', null, undefined, 0), javascript doesn't need to evaluate the rest of the expression as it is false anyway. However it doesn't return false, but the first falsy value. However if a is truthy, it need to evaluate the rest in order to know the result of the expression.

You have the opposite logic when using ||.

Now in your example, {} is truthy, so

(true && {}) // {}
({} && true) // true
({} && true && 42 && '' && true && {}) // '' as first falsy value
floribon
  • 19,175
  • 5
  • 54
  • 66
  • 1
    Why would using boolean operators not give me a boolean when evaluated, though? – william.taylor.09 Apr 29 '15 at 21:07
  • 2
    Because that's how Javascript is made, it avoids to create yeat another boolean value by just returning to you the one that has the truthy/falsy value you expect. You can use `!!val` to get the real boolean value out of a truthy/falsy though. – floribon Apr 29 '15 at 21:15
0

This is due to truthy and falsy logic in JavaScript. All objects that are not: undefined, null, false or 0 are truthy. The && and || operands are evaluated left to right and short-circuit. The expression evaluates to the value of the last evaluated operand. eg:

true && false // will evaluate to false
true || false // will evaluate to true
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114