How to Recognize an Array

A common question is: How do I know if a variable is an array? The problem is that the JavaScript operator typeof returns "object":

   var fruits = ["Banana", "Orange", "Apple", "Mango"];
   typeof fruits;  
<== typeof returns object

The typeof operator returns object because a JavaScript array is an object. To solve this problem you can create your own isArray() function:

   function isArray(myArray) {return myArray.constructor.toString().indexOf("Array") > -1;}

HTML file: Displayed by browser:
<body>
<h4>Using typeof operator on an array:</h4>
<p id="demo"></p>
<hr />
<h4>"Home made" function, used on an array:</h4>
<p id="demo1"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = typeof fruits;
document.getElementById("demo1").innerHTML = isArray(fruits);
function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>
</body>

Using typeof operator on an array:


"Home made" function, used on an array:

The function above always returns true if the argument is an array. Or more precisely: it returns true if the object prototype of the argument is "[object array]".

BackTable of ContentsNext