I understand that ==
in JavaScript is comparison with type coercion. And I know that the following statements are true
:
'' == false;
' ' == false;
'0' == false;
'\n' == false;
However, I can't get a comparison with 'hello' on the left side to be true:
'hello' == true; // no this is false
'hello' == false; // no this is false
'hello' == 1; // no this is false
'hello' == 0; // no this is false
Is there anything 'hello' can be compared to which results in true
other than 'hello'?
Here's one:
http://jsfiddle.net/jfriend00/KSgwb/
Or another:
http://jsfiddle.net/jfriend00/hKx9x/
If you study the coercion rules for
==
, you will find that the only thing that will satisfy==
with"Hello"
is something that already is a string that is"Hello"
or something that has a.toString()
method that returns"Hello"
.That can be done in as many creative ways as you want by joining an array, returning the string directly, processing a bunch of character codes that combine to form that string, etc... But, in the end,
.toString()
has to return"Hello"
in order to satisfy the==
test.If you aren't allowing the thing you're comparing to to have
"Hello"
in it in any way or be able to produce that string upon demand, then NO there is nothing else that will satisfy==
except something that produces the string"Hello"
when asked to coerce to a string.Here's a layman's description of the type coercion rules for Javascript: http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html
In a nutshell, here are the coercion rules when a string is involved:
If both types are a string, then the comparison is
true
only if the two strings contain exactly the same characters.If one is a string and the other is a number, then try to convert the string to a number and compare that to the other number. Since
Number("Hello")
isNaN
, this will never work for a number since NaN can't be==
to another number.If one is a string and the other is an object, call the internal method
valueOf
if it's defined ortoString
if it's not defined and compare the result of that to your string.If one is a string and the other is a Boolean, convert both to a number and compare them. Since
Number("Hello")
isNaN
, it will never match a Boolean which will either be0
or1
when converted to a Number. For example:true == "1"
.