Alexander Dickson

Null or Undefined in JavaScript?

As you know, JavaScript has two nothing types, which are null and undefined. When writing your code or designing an API, which one should you use?

By example

If we look at the W3C DOM API, we can see it uses null to represent no value. For example, if you use document.getElementById() with an id that doesn’t exist, you will be greeted with null.

If we also look at the JavaScript standard library API, you can see something similar. For example, if you use String.prototype.match() and there are no results, you are again met with null.

We can clearly see that two very important APIs use null as the nothing value. Although I can hear you also saying when should the DOM API ever be used as a good example?!?. Well, it has been copied before (e.g. DOMDocument in PHP) and it isn’t too bad.

There are other projects that use undefined, such as trying to get the value of a non-existing attribute in jQuery using $.fn.attr(). But we all also know jQuery isn’t the best example of good API design.

Less confusion

There are things in JavaScript which produce undefined, such as..

  • Function with no return value
  • Object property lookup that doesn’t exist
  • Referencing function argument that wasn’t passed

For this reason, I believe when designing an API or just writing your own code, null is the best choice.

If you query an object and get back null, you know the property has been set explicitly (i.e. it wasn’t a typo). If you get back null from a function, you know the intent was to say nothing, not simply a function that returned undefined by default.

Which one to use?

I recommend using null for your intention of nothing here, as it is line with existing JavaScript APIs and you will never be left scratching your head, thinking was the author’s intention here to return undefined or did they simply not have a valid return value, for example. Of course, proper API documentation would cover this, but then the API is less discoverable.

Can I easily check for both?

It’s worth noting too that you can easily check for the null and undefined types by using the double equals on either of them.

isItNullOrUndefined == null;
isItNullOrUndefined == undefined;

This works because of steps 2 and 3 of the The Abstract Equality Comparison Algorithm.

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows: […]

  1. If x is null and y is undefined, return true.
  2. If x is undefined and y is null, return true.


Want to discuss this post? Just mention me @alexdickson.