Why is 1=='true'
false?
If 1=='1'
is true and 1==true
is true.
If JavaScript compares only values not the types in the ==
scenario.
Why is 1=='true'
false?
If 1=='1'
is true and 1==true
is true.
If JavaScript compares only values not the types in the ==
scenario.
It's because of type coercion.
In effect, this is what JavaScript is trying to do on your behalf when using the ==
operator.
1 == Number('true'); // 1 == NaN
1 == Number('1'); // 1 == 1
1 == Number(true); // 1 == 1
When two different types are compared using ==
, JavaScript attempts to coerce them to the same type for comparission.
You can read more about the algorithm here: http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html