[Solved] How exactly does JavaScipt’s data-type convertion work for “==” operator?


As Crockford says: “The rules by which they do that are complicated and unmemorable.” The spec defines them all in section 11.9.3 (pointed out by @Oriol in a comment to OP).

For the two cases you provided:

if ( 42 == true ) // false ( Only 1 is true )
if ( "Hello World" == true ) // false ( false for any string )

In case 1, y is a Boolean, so it gets converted to a number (step 7). The number conversion of true is 1. So now we’re evaluating 42 == 1. This is obviously false.

In case 2, y is again a Boolean, but this time, x is a string. Per step 7, y is converted to a number, so the comparison is now "Hello World" == 1. Per step 5, x is now converted to a number. The numerical representation of an arbitrary string is NaN. Now NaN == 1 is being compared. As it says in step 1ai, that’s false.

Again, as Crockford said…

2

solved How exactly does JavaScipt’s data-type convertion work for “==” operator?