Monday, August 4, 2008

JavaScript type checking and "isArray" function

Now javascript is a loosely typed language. What do I mean by that? It means just one "type" of variable exists in javascript represented by "var". Even declaring objects of your own type is done in the same manner. This is unlike Java or C++ in which the basic data types are declared as:
int a = 10; string b = "hello world"; ...

In JS, all variables (and even functions) can be referenced by using simple "var" declarations. For example, var a = 10; var b = "hello world";...

Now this causes a problem in checking the type of any object passed into a function. For example, when a function is expecting a string but the callee passes in an integer as a parameter, the function may falter. To do this, checking the type of the variable being passed in can help avoid unexpected errors and continue program execution even when an error occurs or using appropriate error handling capabilities (which I shall speak of on another post).

One of the most common operations when dealing with JSON(JavaScript Object Notation) during AJAX communications is the need to check if the returned object is a single object or an array of similar objects. For doing this there are a variety approaches:
function isArray(obj){
return obj && (obj.constructor == Array);
//return obj && (obj instanceof Array || typeof obj == "array"); //DOJO toolkit approach
/* if(obj.constructor.toString().indexOf("Array") == -1)
return false;
return true;*/
/* if(!obj || typeof obj == "string")
return false;
return obj.length != null; */ //had to use this for Nokia S60 browsers since constructor wasn't recognized

I found the first solution very concise and works on most modern browsers. A useful piece of information is that the "===" (triple equals to) checks for type equality compared to the "==" which checks only the values, which can be used in various other situations.

I'll leave this topic open to debate. There's no one perfect solution on every platform for this, primarily due to the differences in implementation in the various browsers.


No comments: