Why does typeof array with objects return "object" and not "array"?

Johan picture Johan · Oct 21, 2012 · Viewed 116.1k times · Source

Possible Duplicate:
JavaScript: Check if object is array?

Why is an array of objects considered an object, and not an array? For example:

$.ajax({
    url: 'http://api.twitter.com/1/statuses/user_timeline.json',
    data: { screen_name: 'mick__romney'},
    dataType: 'jsonp',
    success: function(data) {
        console.dir(data); //Array[20]
        alert(typeof data); //Object
    }
});​

Fiddle

Answer

gdoron is supporting Monica picture gdoron is supporting Monica · Oct 21, 2012

One of the weird behaviour and spec in Javascript is the typeof Array is Object.

You can check if the variable is an array in couple of ways:

var isArr = data instanceof Array;
var isArr = Array.isArray(data);

But the most reliable way is:

isArr = Object.prototype.toString.call(data) == '[object Array]';

Since you tagged your question with jQuery, you can use jQuery isArray function:

var isArr = $.isArray(data);