CrazySynthax
CrazySynthax

Reputation: 15058

Javascript: "truthy" values for non-empty strings

It's said that non-empty string in Javascript is considered "truthy". It explains why the code:

if ("0") { 
    console.log("OK")
}

prints "OK".

However, why does the code:

true == "0"

returns false?

Upvotes: 1

Views: 645

Answers (1)

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

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)

So, while comparing true == '0', it first converts both into numbers.

Number(true) == Number('0') which evaluates to 1 == 0.

Hence the answer is false.

Upvotes: 3

Related Questions