undefined. When writing your code or designing an API, which one should you use?
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
String.prototype.match() and there are no results, you are again met with
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.
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
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
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.
x == y, where
yare values, produces
false. Such a comparison is performed as follows: […]
Want to discuss this post? Just mention me @alexdickson.