Sunday, January 8, 2012

JavaScript: Check whether a sub object is defined in a multi-object chain

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.

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.

2 comments:

Interesting facts said...

I have no words for this great post such a awe-some information i got gathered. Thanks to Author.
youtube html5 player| html5 converter

Igor Stojkovic said...

Can't you just do something like:

var isDefined = false;
try {
obj.that.doesnt.exist[0];
isDefined = true;
}catch (e) {}

Also like this you can just put the code that expects this var in try block and you can nicely handle the case when it isn't defined in catch block.