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?
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.
Number(true) evaluates to 1, so if you compare any other value, true == '2' it evaluates to 1 == 2 which is false.null and undefined both are considered as false values in javascript. So if you are talking about true == null or true == undefined, you can look in either way true == false or 1 == 0 ( Number(null) = 0 ), both will result in false value.Boolean({}) and Boolean(string). To keep it simple, if any of the values in == is Number, the values are converted into Number(), and for others, it is converted into Boolean().
"0"is coerced to a number in the second case.true == "1"for example returnstrue0,falsewill be coerced totrue.