Tuesday, June 2, 2009

How to check whether a variable has been declared from Javascript

Sometimes we declare javascript variables from serverside pageload method and use it in a common javascript file's method. The problem is, when that common javasript method is used by another serverside file, it might find that variable undefined. The best way to check is use typeof method of javascript. Consider the following method:

if(typeof(uxDocumentsOrImagesRadioButton)!= 'undefined'){

var thisradioGroup = document.getElementById(uxDocumentsOrImagesRadioButton);

uxDocumentsOrImagesRadioButton variable is declared from a page's pageload method. But if another page wants to use this method before that variable has been declared, then it will throw error. So, we need to check whether the variable has been declared previously.

No comments: