Equal Suffering in JavaScript
Thu Aug 7th 2008, 7:39pm
/sigh
<script type="text/javascript">
document.write("0 == \"\": " + (0 == "") + "<br />\n");
</script>
yields:
0 == "": true
Yes, zero is equal to a blank string in JavaScript.

This bit me today in a form validation function in a publicly-released app and marred what was otherwise a triumphant rewrite of someone else's steaming heap of cow dung (trust me on this one). I suppose there's a lesson there, for as well-intentioned as I was, but I'm not going to get into it.

As I discovered, == performs type coercion and, to JavaScript, 0 is the same thing as an empty string (nothing?). It helps a little to see that 0, "", and false are all equal. But then, a little frightening that a string full of whitespace is also equal to false but not equal to an empty string (transitive property, anyone?).

The === (triple equals) operator is available if you want exact type and value matching:
<script type="text/javascript">
document.write("0 === \"\": " + (0 === "") + "<br />\n");
</script>
yields:
0 === "": false
But watch out! You probably want coercion most of the time (e.g. strings in input fields to ints). Just be aware.

For the curious there's plenty more info on the topic out there. A good reference is this matrix of == and === equalities.