1

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/

Sampson
  • 265,109
  • 74
  • 539
  • 565
Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • Because it's Javascript. – Etheryte May 28 '15 at 22:25
  • look here: http://stackoverflow.com/questions/523643/difference-between-and-in-javascript – Raúl Martín May 28 '15 at 22:28
  • possible duplicate of [Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) – ecarrizo May 28 '15 at 22:30

2 Answers2

7

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:

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

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.

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • As an addon note, this same thing is also done in the PHP language. – Chris May 28 '15 at 23:01
  • Can anyone tell, why the casting is to number and not to string? As in my opinion, many more things can be expressed via a string then via a number, number seems a little bit limited to me this way. – Adam Baranyai May 29 '15 at 12:19
3

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?

Community
  • 1
  • 1
ecarrizo
  • 2,758
  • 17
  • 29