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?
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?
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
.
a && b
will 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
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