hh54188
hh54188

Reputation: 15626

Javascript: the confuse about comparison "2 == true"

Here is a javascript comparison:

2 == true //false

it's said, the reason why return false, is because the comparison convert the true to Number datatype, and result is 1:

console.info(Number(true)) // 1

My confuse is, why the comparison don't convert the number 2 to Boolean datatype

console.info(Boolean(2)) // true

and the 2 == true result could be true ?

Upvotes: 3

Views: 2336

Answers (2)

Jhankar Mahbub
Jhankar Mahbub

Reputation: 9848

== does implicit conversion to compare. In this case 2 is number and true is boolean. The conversion rule is "while comparing a number to boolean, boolean will be converted to number" hence

true is converted to 1

and 2 == 1 will be false.

//similarly, 
2 == false; //false

As false will be converted to 0 and 2 cannot be equal to 0 either.

However, 1 == true. for the same reason as true would be converted to 1 and 1==1

Upvotes: 0

hh54188
hh54188

Reputation: 15626

I find the doc here:

Comparison Operators, which said:

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.

Upvotes: 4

Related Questions