Search code examples
javascriptbooleanexpressionboolean-expression

Why does 0 && a Boolean evaluate to 0 instead of the Boolean?


Why does 0 && and a Boolean evaluate to a 0 instead of the Boolean?

0 && false
> 0
0 && true
> 0

But false && 0 returns false and true && 0 returns true

false && 0
> false

I thought a numeric value and a false expression would return a Boolean always.

1 && false
> false


Solution

  • See the documentation from MDN:

    the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value

    and

    expr1 && expr2: Returns expr1 if it can be converted to false; otherwise, returns expr2.

    Since 0 can be converted to false, and 0 is expr1, it returns 0.