JavaScript: an acceptable use of double-equals? Just.
When I first started learning and writing JavaScript, the recommendation I came across again and again was that the equality operator, ==, or “double-equals” was the devil incarnate. You should always use the identity operator, ===, or “triple-equals” because then you won’t have to battle weird type coercion bugs (and remember it’s not necessarily the time you write the original code that you’ll get tripped up, it’s the time you maintain it for the nth time).
photo © 2008 Nick Farr | more info (via: Wylio)So, imagine my surprise when reading the jQuery library code, I came across several uses of double-equals. What? Have Resig and the gang lost it?
Further investigation showed me the pattern they were using. In all cases, when double equals is used, the comparison is checking against null:
if (someObj == null) { // do something }
OK, so is comparing against null somehow special? Time to refer to the language specification.
Section 11.9.3 of the 5th Edition gives the long-winded answer as a descriptive flowchart. In essence, the rules for when one side is null are as follows:
- if both sides are
null, returntrue; - if one side is
undefinedand the other isnull, returntrue; - otherwise, return
false
Note that this is more restrictive than just writing:
if (someObj) { // do something }
since this also allows the other four falsy values (false, 0, NaN, "") to pass through.
And it’s also simpler than writing:
if ((someObj === undefined) || (someObj === null)) { // do something }
which is what it means precisely.
But, man, reading code that uses this construction brings me up short every time. It just seems to be a violation of best practices.
Now playing:
O'Neal, Alexander - Criticize
(from Hearsay)




