Safely referencing objects in javascript (understanding null and undefined)

Part 1

Javascript is a finicky language. If you don't have an in-depth knowledge of the language specifications, some of the little nuances can really throw you off.

One area in particular where I've noticed a lot of confusion among javascript programmers is regarding the null and undefined types. In this article, I'm going to examine the difference between null and undefined (yes, there is a difference, subtle though it may be).

Then, I'm going to talk about what roll the null and undefined types play when trying to determine if it is safe to access a property or method of an object (or whether or not it is even safe to access the object itself).

Finally, I'm going to propose a solution for safety checking before attempting to access some object's properties or methods.

Let's get started!

What's the difference between the null and undefined types in javascript? Well, the short answer is: not much. There is a difference to be sure, but generally speaking, it doesn't change the way we write javascript. Still, it's important to understand that difference.

The undefined type

The undefined type has only one value: undefined. It is the value assigned to a variable when you declare it but fail to assign it an initial value.

var aVariable;
alert(aVariable);    // alerts undefined

Note that this is NOT the same as the string, 'undefined'. Let's get something clear right off the bat:

The javascript interpreter will never set one of your variables to 'undefined'.

The only way a variable will be set to the string, 'undefined' is if you yourself set it to 'undefined'. Thus, we can safely eliminate all if conditionals that look like this:

if (someVar != 'undefined') { // whatever }

What you can do sensibly (which involves the string, 'undefined') is check to see if the type of a variable is 'undefined'. Not surprisingly, the type of a variable whose value is undefined is 'undefined'.

var aVariable;    // initial value is undefined
alert(typeof aVariable == 'undefined');    // alerts true
alert(typeof aVariable == undefined);      // alerts false

If that doesn't convince you that undefined is NOT equal to 'undefined', nothing will.

The null type

While undefined is the "value" assigned to a variable that has not explicitely been given a real value, null is actually an object value indicating that a variable references nothing in particular. Don't believe me? Look at the following example:

var aVar;            // undefined
var bVar = null;     // null
alert(aVar);         // alerts undefined
alert(bVar);         // alerts null
alert(typeof aVar);  // alerts 'undefined'
alert(typeof bVar);  // alerts 'object'
alert(typeof null);  // alerts 'object'

Pay particular attention to the last line in the above code snippet. Notice that typeof null yields 'object' whereas typeof undefined yields 'undefined'.

But here's the kicker:

In javascript, the == operator resolves null and undefined as equal.

alert(null == undefined);  // alerts true

So what does this mean? It means that, for the large majority of cases, checking for null is no different than checking for undefined. It means that most of the time, you don't really have to alter the way your write your javascript at all.

var someVar;

if (someVar != null)
  { alert('someVar is not null'); }

if (someVar != undefined)
  { alert('someVar is not null'); }

Even though technically the value for someVar is undefined, both of the above if conditionals will function as expected (neither of them will execute in this case).

However, there is one case you need to watch out for. If, for some reason, you have a need to check for the existence of a variable (you don't know whether or not it was ever declared), then the above examples most certainly won't do. I know some of you won't believe me here, so try this example to prove it to yourself.

if (someVariable != null)
  { // someVariable is not null }

The preceding code example will fail because the variable someVariable was never declared. In this case, our code will fail when the javascript interpreter attempts to execute the statement if (someVar != null).

I've seen a lot of javascripter try to be "ultra-safe" by doing something like this:

if (someVar && someVar != null && someVar != 'undefined' && typeof someVar != 'undefined') { // okay to reference someVar }

The preceding code is a foolish and futile attempt to be "safe" that really just accomplishes a whole lot of nothing (except maybe to reveal that you don't really understand javascript). We've already established that doing: someVar != 'undefined' is silly. And we also know that if (someVar != null) is the more explicit equivalent of if (someVar). So really what we've got here is a lot of silly, bloated javascript. Please don't do it.

So how do you safely check for the existence of a variable? Well, that's a great question (and a perfect lead-in to Part 2 of this article).

Goto page 2 to learn more.

7 thoughts on “Safely referencing objects in javascript (understanding null and undefined)”

  1. Brilliant tutorial, mate! I'm finally working with javascript again for the first time in ten years since hacking around as a teenager; it's the accurate, well-written posts like this one that are filling in so many gaps for me.

  2. Nice post.

    One remark to your statements "[..] frequently using the typeof operator exclusively to check for the existence of a variable [..] is probably a sign of bad program design" and "[indicates] that your objects [..] are too tightly coupled":

    I don't agree here, because I suggest using this check as good practice especially in loosley coupled objects to verify pre-conditions. For instance in setter methods with variant parameters this makes very much sense.

  3. Till,

    Granted, the concept has its proper place, and the scenario you point to makes sense. My point is just that if you don't know what properties/methods exist on an object, and you constantly find yourself "guessing" or "testing the waters" by using typeof to determine if a method or property exists, you might want to rethink the design a tad. In my experience, when programming like that is overused, it leads to unwieldy and difficult to maintain code.

  4. Hello!
    Very Interesting post! Thank you for such interesting resource!
    PS: Sorry for my bad english, I'v just started to learn this language 😉
    See you!
    Your, Raiul Baztepo

  5. Hello ! 😉
    My name is Piter Kokoniz. Just want to tell, that your posts are really interesting
    And want to ask you: what was the reasson for you to start this blog?
    Sorry for my bad english:)
    Piter Kokoniz, from Latvia

  6. @Pieter:

    Thanks for your comments. I started the blog just as a way to keep a programming reference for myself and the things I've learned, and also as a way to share what I've learned with others.

  7. Dude, nice explanation.
    Just a minor typo bug –
    A better solution is to verify the existence of the variable and then verify that it it isn't null.

    if (typeof someVar != 'undefined' && someVar != 'null')
    { // someVar exists and isn't null }
    At this point you can be sure that someVar is safe to access

    The NULL in if condition should not be within quotes. In rest of the page it's what it should be, so certainly it was a typo only.

Leave a Reply

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