When you are in JavaScript mode it is common for you to use
typeof operator to see whether a given variable, object, function etc. is known to JavaScript.
typeof operator to see whether a given variable, object, function etc. is known to JavaScript.
However, many times I find myself writing more complex code because it is a child of a child object that I need to check for a value. This makes for ugly code.
Being rather simple minded I chose to Google for an obvious solution. Unfortunately, nothing was immediately available (or I might be simple missing it). Most people seem to only need to be dealing with the top level object deceleration and, thus, no need for anything else.
So, to make a long story short, I created a simple helper function that does most of the work for me and cleans up the repetitive code. Feel free to use it at your leisure:
/** * Take string input in varName and determine whether it is defined object in Javascript * @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; }
Cheers,
-B.