Use Null Comparisons Sparingly

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.

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-book that explains not just concepts, but also real-world uses of promises.

Download the Free E-book!

The community edition of Understanding JavaScript Promises is a free download that arrives in minutes.