Identifying an array in JavaScript
In JavaScript using typeof operator we can find the type of the variable used in the script. But it sometimes produce some confusing values for the developer especially for the novice ones. Consider the following code
var foo = {
'name': 'Jayaprakash',
'job': 'Web Team Lead'
};
If you want to determine the type of the object literal foo it is quite simple
console.log(typeof foo); //Outputting it to the browser console
The output would be ‘object‘. Pretty simple, right?
Now consider an example with an Array
var foo = []; foo.push(1); foo.push(2);
You want to determine the type of the array vaiable foo
console.log(typeof foo);
The output would be ‘object‘. Bit confusing you may be expecting array as the output. This is because JavaScript treats arrays as object (most of the items in JavaScript are considered as objects) in it. As a result when you determine the type of it, it will give you a value of object.
The question at this point is, is there any way through one can determine whether a variable is array or not? Yes we have a simple method for doing that
var isArray = function(arr){
return Object.prototype.toString.call(arr).toLowerCase().indexOf('[object array]') !== -1;
}
This function will return true if the argument is a JavaScript array else it will return false.