Checking for null or undefined, and introducing typeof === undefined

It can be difficult to decide whether you should be checking for null or undefined in JavaScript; on the face of things it may seem that they do the same job.

Fortunately, there’s quite an easy to follow rule with this; unless you specifically set something to null, you should most likely be checking for undefined.

As ever there are exceptions, and here it is; if using document.getElementById(), null; is returned if no element could be found.

Let’s go through some situations where things will be undefined:

  1. Checking a variables default value. An un-initialized variable will be undefined. Caveat though; if a variable is undeclared, this will throw an error.

    var foo;
    alert(foo === undefined); // true
    alert(bar === undefined); // error
  2. The default return value of a function.

    function foo() { } 
    function bar() { return; }
    alert(foo() === undefined); // true 
    alert(bar() === undefined); // true
  3. The value of an unspecified attribute in an Object

    var obj = {};
    alert( === undefined); // true
  4. The value of an out-of-bounds array index

    var array = []; 
    alert(array[100] === undefined); // true

However, should you really be checking against undefined, are there any caveats of doing so? It turns out there is!

  1. As mentioned above, comparing an undeclared variable against undefined will throw a ReferenceError: foo is not defined.
  2. undefined is a property on the global object. Prior to ES5, this value was writable; allowing problems like this;

    var foo;
    undefined = 42;
    alert(foo === undefined); // false
    alert(42 === undefined); // true

To avoid these caveats, it turns out you should use the typeof operator instead, and compare against the Undefined type:

var foo;
undefined = 42;

alert(typeof foo === "undefined"); // true
alert(typeof 42 === "undefined"); // false
alert(typeof bar === "undefined"); // true- no error!

2 thoughts on “Checking for null or undefined, and introducing typeof === undefined

  1. Yes it is, == will attempt to convert the operands to the same type before applying a strict comparison, where-as === will perform no conversion. You can see a more detailed explanation on the MDC site!

Leave a Reply

Your email address will not be published. Required fields are marked *