isArray Function
When writing generic JavaScript functions (which we do as much as possible), you need to account for developers of all levels of experience using your generic function. This means preventing errors from happening if the developer sends in something unexpected as a parameter. The most recent example of this is working with an array as a parameter. That led us to wonder how to check a variable to know if it's an array in JavaScript. There's no built-in "isArray" function like there is with other languages. And, to make matters worse, strings are really arrays of characters. So checking value[0] can give you a valid value even if value is a string instead of an array.
The key to checking to see if a variable is an array is checking to see how the variable was initially created. This is done with the constructor property of the variable. This returns the internal function used to create the variable. Check it out sometime using the statement alert(myVariable.constructor). Using this knowledge, here is our isArray function:
function isArray(obj) {
if (obj.constructor.toString().indexOf("Array") == -1)
return false;
else
return true;
}
If the passed-in object is an array, the value true will be returned.