Reputation: 3867
Why does JavaScript consider the value 0
as being equal to an empty string?
defValue = 0;
if ( defValue == '' ) defValue = null;
alert( defValue ); // alerts null
defValue = 1;
if ( defValue == '' ) defValue = null;
alert( defValue ); // alerts 1
Fiddle: http://jsfiddle.net/L55n0tvj/
Upvotes: 0
Views: 95
Reputation: 268344
JavaScript does something really interesting when checking the equality of two values with ==
. If the values are different types, such as a Number and a String, then an initial conversion has to be made to bring the two types into harmony.
The ECMAScript Language specification provides the algorithm used to determine the equality between two values, as well as which value will be converted in the event the two are of different types.
Section 11.9.3, Abstract Equality Comparison Algorithm, outlines the steps taking for the expression x==y, which is what you are inquiring about here. Pay special attention to Step 4 of the algorithm:
As a result of this, our empty string must first be converted to a number. According to Section 9.3.1, ToNumber Applied to the String Type, the mathematical value of an empty string is 0.
Our x==y expression is now 0==0, which is clearly true
.
If you would like to avoid the casting, you should consider checking Strict Equality instead, described in Section 11.9.6. If the two values are not the same type, the algorithm immediately returns false
.
Upvotes: 7
Reputation: 2809
Short: == make any necessary type conversions and then evaluate, so in this case the empty string after the conversion is of the same type as 0;
0 == '' // return true.
So you need to use strict comparison instead (===);
0 === '' // return false;
Long:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Upvotes: 3