Defensive coding (Advice)

Allowing your scripts to be downwards compatible and coding for portability and robustness.

Coding defensively is to check for the existence of a feature before using it. Also to check that objects are defined before trying to modify their properties. You can check the version of the browser and switch various features of your scripts on and off accordingly.

With a little thought and planning, you can contrive your script design so that it degrades gracefully if it is run on less capable browser versions than that which you originally designed it for.

Defensive coding also covers-cross platform and cross-browser support. Running scripts in different browsers often exposes the differences between them. This may be simply a property value that is available in one context but not another. A more serious problem might be an entire object class that is missing from particular implementations.

Sometimes the differences are more subtle than that, and you may just find that a document object model needs to be traversed in a different way, depending on the browser being used.

Example code:

   // Check for the existence of an object before using it

   if(document.layers)

   {

   document.write(document.layers);

   }

   else

   {

   document.write("There is no layers array in this browser!");

   }

See also:Browser version compatibility, Compatibility, Cross browser compatibility