Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (true && {}) evaluate to {}, but ({} && true) evaluates to true? [duplicate]

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?

like image 899
william.taylor.09 Avatar asked Dec 19 '22 04:12

william.taylor.09


1 Answers

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.

like image 72
Pointy Avatar answered Dec 24 '22 01:12

Pointy