This is one of the easier problems I have come across which is most likely why I never wrote down the solution.
How to tell if a var (variable) is an Array? I have come across this question a number of times over the years and each time I search for the solution I found many others with the same question but often took more work to find the answer.... So here it is.
With a var in JavaScript it is not enough to test using the .length property as string also have a length.
instanceOf
This example uses the instanceof Operator to test this returns a boolean [true|false]. This is my preferred option but it is not the only one available to you. This will work only when the array was created in the same context, by this I mean where the array was created in the same window, script or frame.
if (testVar instanceof Array) {
alert('testVar is an Array!');
} else {
alert('testVar is NOT an array');
}
The example we will receive an alert window declaring the true nature of the testVar variable.
typeOf
The following example is useful in the case where the array was initialised or created else where and passed to the method which will test it. The typeof Operator is useful for returning the type of an object. There are a number of interesting features to note when using this operator. Firstly an array is of type object, but it is not the only one that will return object it's type. Date, Math, null and Object are all of type object also. This means an extra level of validation is required to be certain that you are dealing with an array. This is where the .length function mentioned above comes in handy.
if(typeof(testVar) == 'object'){
if(typeof(testVar.length) == 'number'){
alert('testVar is an Array!');
}else{
alert('testVar is NOT an array');
}
}
What we are testing here in the first line is that the testVar is in fact of type object and so ruling out a string object(which would also have a .length function). The second if statement then tests to ensure the length function of testVar returns a number as it if was an object of type null for example it would not provide a results of type number and so invoke the "NOT an array" alert. If testVar is of type array is will return a length of type number and invoke the "is an array" alert. This extra level of logic is due to the lack of an infallible method of object type identification.


