> "s" && true;
true
> true && "s";
's'
I thought these two expressions would return same values.
Why not? How does it work?
> "s" && true;
true
> true && "s";
's'
I thought these two expressions would return same values.
Why not? How does it work?
See MDN:
expr1 && expr2: If expr1 can be converted to true, returns expr2; else, returns expr1.
&&
evaluates to the value of the last truthy expression, so if both operands are truthy, the whole thing will evaluate to the first operand.
If the first operand is falsey, it'll evaluate to the (falsey) value of the first operand.
Similar to ||
, you can think of it as evaluating to the value of the expression that determines the final value. (If evaluating the left operand provides a truthy result with ||
, there's no need to evaluate the right - similarly, if the right operand produces a falsey result with &&
, there's no need to evaluate the left.)