close
The Wayback Machine - https://web.archive.org/web/20150916123740/http://javascript.about.com/od/problemsolving/a/conditionaltesting.htm

Condition and Assignment Error Handling

The way that we code our JavaScript can reduce the opportunity for errors to get into our code. Here we are going to look at a couple of ways that you can make minor changes to your code in order to protect against some errors.

The first of these errors we are going to look at is how to avoid having our JavaScript crash because the particular implementation doesn't support a particular object whose properties and methods we are trying to access. One example of this would be with older browsers such as Netscape 4 and IE4 which do not support the DOM methods. A slightly more modern example would be where some browsers have introduced document.getElementsByClassName while others have not.

Suppose we take a specific example of this where we need to reference document.getElementsById(''warn').style and we don't want our code to crash if getElementById isn't supported.

To protect against this sort of error we use the && operator as follows:


document.getElementById && document.getElementsById(''warn').style

Our code now has a value of false if the call isn't supported instead of crashing because the stylle property can't be referenced. So now we can simply skip over the subsequent processing if the expression is false rather than having our code crash.

For a slightly longer example that shows how you might use this in your actual code consider:


var warnstyle = document.getElementById &&
document.getElementsById(''warn').style;
if (warnstyle) { // code to process style if supported goes here
}

The second of the errors that we are going to consider is where we have a variable or property that doesn't exist or evaluates to false where we want to supply it with a different default value. To do this one we use the || operator like this:


myObject.propertyone || 'mydefaultvalue'

With this code where propertyone does not exist or is false the value following the || is used instead.

This code can also be used to test for the existence of several different fields returning the first one that exists as for example with:


function vpWidth() {
return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}