Wednesday, May 28, 2008

Check availibility of user-defined objects before you using them

Problem:
Oftentimes, programmers take the existence of user-defined variables, properties and objects for granted, which in turn results into unstable code that works when those objects exist and fails when they don't.

Solution:
Always check the existence of the following objects before manipulating them:
  • DOM objects
    var elem_to_test = document.getElementById('ad-unit');
    if (elem_to_test) {
    // proceed with code
    }
  • Global JavaScript variable/object
    if (typeof YAHOO != 'undefined') {
    // proceed with code
    }

    OR

    if (window.YAHOO) {
    // proceed with code
    }
  • Object property
    if (window.obj && obj.property) {
    // proceed with code
    }

No comments:

Blog Archive