Bruno Brant
Bruno Brant

Reputation: 8554

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.

Upvotes: 7

Views: 21139

Answers (2)

Thaddeus Albers
Thaddeus Albers

Reputation: 4192

underscore js has a function for this _.isUndefined()

from https://underscorejs.org/#isUndefined

isUndefined _.isUndefined(value)
Returns true if value is undefined.

example:
_.isUndefined(window.missingVariable);
=> true

lodash has a similar function. see https://lodash.com/docs/4.17.11#isUndefined

Both have similar functions for isNull too.

I find the functions are useful for others to know what is being tested for.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

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.

Upvotes: 31

Related Questions