Checking for JavaScript Variable Definitions

In some cases you need to be able to check if a variable has been defined, and if it has a value.

I recently had a problem where I needed a function to check if a variable had been defined, and if not, to return a default value “1”.

The following code will check if the variable is defined, and if it is, it will also check and make sure that it isn’t null, before returning the value.

 

function GetDefaultModuleId(){
    if (typeof(csDefaultModule) == "undefined"){                            
        return "1";
    }else{
        if (csDefaultModule == null){
            return "1";
        }else{
            return csDefaultModule;
        }                    
    }
}

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s