Checking the undefined

06 June 2011

How do you know if a variable has been declared? It would be nice if we could do this:

if (MickyMouse)

Unfortunately, this will break if MickyMouse hasn’t already been defined. As you’re referencing a variable that the script (at that state) isn’t aware of. The most robust way to do this, is to check if a variable is/n’t “undefined” using the typeof method.

if (typeof MickyMouse === 'undefined') // you may want to define it here

Which can also be written as:

if (typeof(MickyMouse) === 'undefined') // as above

This to me is a little too wordy, so is there a better way to do it? For the most part, we want to know if the value of the variable returns a truethy value (which is anything that isn’t falsey).

What is a Falsey value?

0         //zero
false     //false
""        //an empty string
null      //a null value
undefined //an undefined value

The property of Objects

Check if an object has a property or method. We’re going to try and put a hat, gloves and shirt on Micky Mouse, if he wears them.

MickyMouse = {
    wearsAHat : 0,
    wearsGloves : 2
}

We could use the typeof method, but there’s a simpler way. As objects check for a truethy property values without throwing errors for undefined properties, we can do this:

if (MickyMouse.wearsGloves) { // defined with a truethy value of 2
    MickyMouse.gloves = "white";
}
if (MickyMouse.wearsAHat) { // defined with a falsey value of 0
    MickyMouse.hat = "cap";
}
if (MickyMouse.wearsAShirt) { // undefined, falsey
    MickyMouse.shirt = "t-shirt";
}
alert(MickyMouse); // { gloves : "white", wearsAHat : 0, wearsGloves : 2 }

Global Scoped variables

Given that object properties will return their value (above) and that every global variable is a child of the window object, we can check the window object for that property.

if (!window.MickyMouse) MickyMouse = {};

I like it, it’s more legible and makes more sense to me, as you’re acknowledging the variable is global. I’m not sure on how costly in performance this is in comparrison to the typeof method (to be investigated). It can also be written as:

MickyMouse = window.MickyMouse || {};

Though this requires you to redefine the YAHOO object if it exists, which is a redundant redefinition (looks pretty though).

So….

  • One thing that will work for everything is the typeof check.
  • Objects don’t throw errors when checking for an undefined property, so you don’t really need to use the typeof method.
  • Globally scoped variables are defined to the window object (so you can use the object property check)

Matt Sain

Ramblings of a developer, designer and child subscribe

This blog is a public GitHub repository. If you find an error I will not be surprised... but if you fork and edit the blog and send me a pull request you'd be pretty awesome in my book.

Featured Repos