1

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?

4

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I don't think, that's correct. But, Number(true) evaluates to 1, so if you compare any other value, true == '2' it evaluates to 1 == 2 which is false.
what about null and undefined ?
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.
What happens if we have an object and a string? How do we convert an object to a string?
In Javascript,` Objects ( {} ) ` are ` true ` values. And, any string other than ```(empty string)` is also true value. To check, you can use 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().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.