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.

Was this helpful? If you found this post helpful, I would very much appreciate your support. Donations of any amount gratefully accepted.