Defensive Programming JScript

By ecliptic

Over the course of programming in javascript, one can easily lose the concept of defensive programming in that language. I mean come on… it’s likely that the javascript you put in your site is just for fancy popup boxes or capturing keys, etc, and this is not really a crucial factor to consider for your site to properly run.

So in essence, most of us simply put code like so…

function Test()
{
if( document.getElementbyId('mycheckbox').Checked )
//do something
}

We all know that javascript does not have an assert of any kind, but would you necessarily use this same kind of logic in your code behind? I assume not. You would probably want to check to see if this object exists first. Granted, you do not want to always do this because then your code becomes a “Coding Horror”, but nonetheless, it should probably be at least considered in your javascript code, especially if you’re attempting to write generic javascript functions.

Try this on for size:

function Test()
{
var checkbox = document.getElementById('mycheckbox');
if( checkbox != null )
// do something
else
// do something else
}

So next time you get a javascript error in your code, instead of “fixing” it, try a little defensive programming. It could make your life a lot easier, and besides, putting a little extra load on the client never hurts right? :)

Leave a Reply