Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Bruno Brant Avatar asked Jul 28 '16 23:07

Bruno Brant


People also ask

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.

Why is null == undefined true?

Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.

Should I use null or undefined?

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".


1 Answers

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.

like image 170
T.J. Crowder Avatar answered Nov 05 '22 09:11

T.J. Crowder