I\'ve been reading Douglas Crockford\'s JavaScript: The Good Parts, and I came across this weird example that doesn\'t make sense to me:
\'\' == \'0\'
The answer to this question has to do with how JavaScript handles coercion. In the case of ==
, strings are coerced to be numbers. Therefore:
'' == '0'
is equivalent to '' === '0'
(both are strings, so no coercion is necessary).
0 == ''
is equivalent to 0 === 0
because the string ''
becomes the number 0
(math.abs('') === 0
).
0 == '0'
is equivalent to 0 === 0
for the same reason.
false == undefined
is equivalent to 0 === undefined
because JavaScript coerces booleans to be numbers when types don't match
false == null
is equivalent to 0 === null
for the same reason.
null == undefined
is true because the spec says so.
Thanks for asking this question. My understanding of ==
is much better for having researched it.