Bruno Brant Bruno Brant - 4 months ago 11
Node.js Question

Checking for null or undefined

Although there are semantic differences between JavaScript's

null
and
undefined
, many times they can be treated as the same. What's the preferable way of checking if the value is either null or undefined?




Right now I'm doing the following:

if (typeof value === "undefined" || value === null) {
// do something
}


Which is pretty verbose. I could, of course, create a function for this and import everywhere, but I'm wishing that there's a better way to achieve this.

Also, I know that

if (value == null) {
}


Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.

Answer

Also, I know that

if (value == null) {
}

Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.

No, it gets the job done 100% of the time. The only values that are == null are null and undefined. 0 == null is false. "" == undefined is false. false == null is false. Etc. You're confusing == null with falsiness, which is a very different thing.

That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write value == null or the explicit one you're currently using (or if (value === undefined || value === null)) is a matter of style and in-house convention. But value == null does do what you've asked: Checks that value is null or undefined.

The details of == are here: Abstract Equality Comparison.