Skip to content

Instantly share code, notes, and snippets.

@subimage
Created April 18, 2012 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subimage/2411247 to your computer and use it in GitHub Desktop.
Save subimage/2411247 to your computer and use it in GitHub Desktop.
Javascript method to check if a chained object is defined.
/**
* Take string input in varName and determine whether it is defined object in Javascript
* ...like isDefined('foo.bar.baz');
* Better than doing if(foo && foo.bar && foo.bar.baz){}
* @param {String} varName
* @return {boolean}
* @author Bilal Soylu
*/
function isDefined(varName) {
var retStatus = false;
if (typeof varName == "string") {
try {
var arrCheck = varName.split(".");
var strCheckName = "";
for (var i=0; i < arrCheck.length; i++){
strCheckName = strCheckName + arrCheck[i];
//check wether this exist
if (typeof eval(strCheckName) == "undefined") {
//stop processing
retStatus = false;
break;
} else {
//continue checking next node
retStatus = true;
strCheckName = strCheckName + ".";
}
}
} catch (e) {
//any error means this var is not defined
retStatus = false;
}
} else {
throw "the varName input must be a string like myVar.someNode.anotherNode[]";
}
return retStatus;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment