faya
faya

Reputation: 5725

JavaScript implicit conversions in equality with a string

How does JavaScript behave for the comparisons true == "true" and (0 == "0")?

Upvotes: 1

Views: 654

Answers (2)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827704

Type coercion aware operators (== and !=) can yield some wierd results:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true

false == 'false'   // false
false == '0'       // true

false == undefined // false
false == null      // false
null == undefined  // true

' \t\r\n ' == 0    // true

The === and !== strict equality operators are always preferred.

Upvotes: 3

redsquare
redsquare

Reputation: 78677

When using == or != if the types of the two expressions are different it will attempt to convert them to string, number, or Boolean etc

However you can use the identity comparison === or !== where no type conversion is done, and the types must be the same to be considered equal.

Upvotes: 3

Related Questions