0
    > "s" && true;
    true
    > true && "s";
    's'

I thought these two expressions would return same values.
Why not? How does it work?

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • In simple terms, `&&` will return false for falsey expression or last truthy value (*not true*) – Rajesh Oct 16 '19 at 07:36
  • As Rajesh said and marked. However I'd like to add that you can use the boolean function to convert it to a Boolean value however by using `!!(false && "s");` but that's besides the point of this question. – Adrian Oct 16 '19 at 07:37
  • The expression simply tests for each part being NOT 0 and in both cases "s" is not 0 and true is not 0, the expression is saying test1 AND test2, in other words (test1 == true) AND (test2 == true) – SPlatten Oct 16 '19 at 07:38

1 Answers1

1

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.)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320