Comparing values against null is a very popular thing to do in JavaScript, but I fear that typically it’s overused and used in situations when it’s completely inappropriate. Consider the following:

if (sText != null) {
    var aParts = sText.split(",");
}

Suppose this is in a function that has sText as an argument. The intent here it to say, “if the argument was passed in, continue, otherwise, don’t do anything.” This is perfectly fine logic, but in actuality, what you really want to check is to see if sText is a string. The next line uses the split() method, which only exists on a string. In the original scenario, it would be possible for sText to be non-null but still cause an error on the next line. So really, the more appropriate condition would be:

if (typeof sText == "string") {
    var aParts = sText.split(",");
}

Now, you’re ensuring that sText is not only not null (since a null value returns “object” when passed into typeof), but also that the next line will never fail. I’d really like to see more developers using typeof in this way instead of relying on comparisons against null that really do very little to save their code from invalid data.

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.