views:

69

answers:

2

Hello, There is a question. How JS will bevave if we compare if (true == "true") and (0 == "0") ? Is there any other tricky convertions?

+2  A: 

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.

redsquare
+2  A: 

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.

CMS