Safely referencing objects in javascript (understanding null and undefined)

Part 2

In Part 1, I discussed the subtle difference between the null and undefined types in javascript. In Part 2, I'm going to talk about some techniques for safely referencing the properties or methods of an object, as well as how to check for the existence of a variable (if you're not sure that the variable was ever declared).

Let's start with the easiest case first.

Verifying the existence of a variable

Suppose you want to make sure a variable exists before trying to use it. We already know that we can't directly reference the variable (not even to check if it's null), so what do we do? We use the typeof operator.


if (typeof someVar != 'undefined')
  { // someVar exists }

This type of check verifies for us that the variable, someVar exists. This is a good start, but it doesn't mean that we can now go blindy using someVar in our code.

Why not? Remember that typeof null yields 'object'. If someVar were equal to null, its type would not be 'undefined', it would be 'object'. If you try to access properties or methods of a null variable, the javascript interpreter will offer you a very nice run-time error. Clearly not very "safe" code.

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. If you have some idea of the type of object someVar is, you can now safely access someVar's properties and methods. However, determining which properties and methods someVar supports (if you don't know or aren't sure) is a different ballgame entirely (which I'll get to shortly).

All we know at the moment, is that someVar is not of type undefined and that it isn't null. But bear in mind that that's all we know (what someVar isn't). Our if conditional tells us nothing about what someVar is.

If you find yourself frequently using the typeof operator exclusively to check for the existence of a variable, it is probably a sign of bad program design. Afterall, you should know whether or not a variable has been defined in your application. If you're playing a "guessing game," it's probably a hack to avoid run-time errors, and that is a sure-fire sign that your objects that are too tightly coupled. If you fall into this category, I strongly recommend reevaluating your program code.

Safely accessing properties or methods of an object

On the flip side of the coin, suppose you know that a variable exists (it was explicitely declared either through the user of the var keyword or inside of a function declaration). In that case, you don't technically need to do the typeof someVar != 'undefined' check.

Why not? Because in javascript, the == operator resolves null and undefined as equal. However, I still recommend using this check because it is more efficient. EMCAScript language specifictions only mandate that null evaluate to false in an if conditional. The undefined type actually has to be converted to null first, and that is less efficient than checking with the typeof operator straight away.

In fact, if what you're trying to verify is the existence of some method of an object, then my recommendation is to do the following:


if (typeof someVar != 'undefined' && someVar != null)
{
  if (typeof someVar.aMethod == 'function')
    { // okay to invoke someVar.aMethod(); }
}

Actually checking to make sure .aMethod is a function saves us a step because if typeof aMethod yields 'function,' then we know that aMethod can't possibly be null. Furthermore, we know that aMethod isn't merely some property of someVar; it's an executable function, so it's definitely safe to invoke it.

This concept can also be used for properties of an object, if you know what the type a property is supposed to be. Suppose you expect someVar to have a property, .xValue, which is supposed to be a numeric type.


if (typeof someVar != 'undefined' && someVar != null)
{
  if (typeof someVar.xValue == 'number')
    { // someVar.xValue is valid }
}

One caveat here is that typeof only works with native types, not custom objects.


function Cat(name)
{
  this.name = name;
}

var c = new Cat('Felix');
alert(typeof c);  // alerts 'object', NOT 'cat'

Don't be fooled into thinking you can do: if (typeof c == 'cat') { ... }. It won't work.

In this case, you'd need to use the instanceof operator.


var c = new Cat('Felix');
if (c instanceof Cat)
  { alert('c is a Cat object'); }

All of this type checking can get rather tiresome after a while. It doesn't take long to get sick of it, not to mention that it starts to make your code look pretty unweildy. Clearly, some sort of function is in order to help minimize the repetition here.

This leads me to a function, safeRef(..), which you can execute to determine if it is safe to access a variable or a property or method of an object.

To see the safeRef(..) code and explanation, goto page 3 now.

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:)
    Tnx!
    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.
    Cheers!

Leave a Reply

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