Created
April 18, 2012 05:19
-
-
Save subimage/2411247 to your computer and use it in GitHub Desktop.
Javascript method to check if a chained object is defined.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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