The JavaScript Identity Operators
I’ve heard rumors of this before, but didn’t quite grok it. And now that I do, it’s very cool yet very strange. To demonstrate:
js>var n = "1" js>1==n true js>1===n false
Yep, n is both equal and unequal to 1. But what’s up with that === operator? As many of you know, JavaScript is dynamically typed. If you check to see if two objects are equal using ===, JavaScript will try to figure out if they are the same type and, if not, try to get them to that same type. So, in the example above, n is a string with value of 1 and when you compare that to the Number value 1, they are the same.
But === doesn’t do the conversion. Instead, if it sees two objects aren’t of the same type, it says they aren’t equal automatically. This is more in line with how Python and Java work — i.e. statically typed languages. They call this an “identity operator”. Naturally there is a !== operator as well that returns true if the objects are not equal.
In Douglas Crockford’s awesome JavaScript presentations, he recommends always using the identity operators instead of the equality, unless you are purposely comparing to different objects. I tend to agree — not having automatic type casting should reduce bugs as well as improved performance.