Implied string comparison, 0=='', but 1=='1'
According to the Mozilla documentation on Javascript Comparison Operators
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string
What's actually happening is that the strings are being converted to numbers. For example:
1 == '1'
becomes 1 == Number('1')
becomes 1 == 1
: true
Then try this one:
1 == '1.'
becomes 1 == Number('1.')
becomes 1 == 1
: true
If they were becoming strings, then you'd get '1' == '1.'
, which would be false.
It just so happens that Number('') == 0
, therefore 0 == ''
is true
When javascript does implicit type conversions, the empty string literal will match the 0 integer. Do your comparison like this and you'll get your expected result:
alert(1==='') ==> false
alert(0==='') ==> false
alert(-1==='') ==> false
This is just one of the truly hideous mangles that went into the JavaScript compromise. '' and 0 are both uninitialized values (equal to boolean false) and, therefore, equal.
To protect yourself from weird bugs like this, it's better to always use the === operator.
ECMA-262, 3rd edition, 11.9.3 regarding x == y
, step 16:
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
The empty string ''
gets converted to 0
before the comparison.