Fun With Null And Undefined
I’ve been using the great JavaScriptLint tool recently to go over my code. One of the errors that it typically flags is comparison with null, 0, or an empty string, which it says should not be done with == or != because of type coercion. So I dutifully went along and changed all !=null to !==null. The problem is that these don’t do the exact same thing.
Consider if you’re checking for the existence of a property on an object, such as:
if (o.prop != null){
//do something with o.prop
}
The value of o.prop is actually the special value undefined (not null). However, since null == undefined returns true, this code will work as intended. The problem is that null === undefined is false, so if you change the code to use the !== instead, it won’t work as intended:
if (o.prop !== null){
//do something with o.prop
}
Now this code won’t convert the value of undefined and so it’s not equal to null. You could change this to explicitly check for the right value:
if (o.prop !== undefined){
//do something with o.prop
}
This works fine, unless your users may be using an older browser that doesn’t support ECMAScript 3 (which formally defined the undefined special value). The safest way to make the code have the intended effect is to use the typeof operator:
if (typeof o.prop != "undefined"){
//do something with o.prop
}
Now, JavaScriptLint is happy, the code makes senese, and it’s backwards compatible. Phew.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.




3 Comments
Do you know which browser currently does not support ECMAScript 3? Would be interesting, because if this is only true for really old ones the variant with using "undefined" is much nicer, and maybe faster, as there is no slow string compare necessary.
Sebastian Werner on June 15th, 2006 at 5:42 am
Question would be, when do you really want to differenciate between undefined and null?
I always treat undefined as null. Maybe I should rethink this…
José Jeria on June 16th, 2006 at 6:47 am
I tend to think it’s important to distinguish between two because of what they mean. If an argument isn’t included when calling a function, it’s undefined, which is different from explicitly passing in null.
Nicholas C. Zakas on June 16th, 2006 at 6:54 pm
Comments are automatically closed after 14 days.