太極者無極而生 太極者無極而生 - 4 months ago 11
Javascript Question

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

The following shows that

"0"
is false in Javascript:

>>> "0" == false
true

>>> false == "0"
true


So why does the following print
"ha"
?

>>> if ("0") console.log("ha")
ha

jdi jdi
Answer

The reason is because when you explicitly do "0" == false, both sides are being converted to numbers, and then the comparison is performed.

When you do: if ("0") console.log("ha"), the string value is being tested. Any non-empty string is true, while an empty string is false.

Equal (==)

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

(From Comparison Operators in Mozilla Developer Network)