Reputation: 31
While the expression is evaluating as expected for 1 && {}
giving {}
as the answer, however when I flip the operands to make it {} && 1
it gives syntax error.
452:1 Uncaught SyntaxError: Unexpected token '&&'
I was expecting 1 as the result in the latter case. The same behavior is replicated with the || (OR) operator.
Upvotes: 0
Views: 93
Reputation: 1
1 && {}: In this case, 1 is a truthy value, so the evaluation continues to the second operand, {}. Since {} is an object and is considered truthy, the result of the expression is {}.
{} && 1: Here, {} is an object and is considered truthy, so the first operand is truthy. However, when it comes to the second operand, 1, there is a syntactical issue. In JavaScript, the logical AND operator (&&) expects both operands to be expressions or values that can be evaluated. However, 1 is a single token, and it cannot be used as an operand for the logical AND operator without wrapping it in parentheses. Hence, you're seeing a syntax error.
Upvotes: -5