114

What is the best de-facto standard cross-browser method to determine if a variable in JavaScript is an array or not?

Searching the web there are a number of different suggestions, some good and quite a few invalid.

For example, the following is a basic approach:

function isArray(obj) {
    return (obj && obj.length);
}

However, note what happens if the array is empty, or obj actually is not an array but implements a length property, etc.

So which implementation is the best in terms of actually working, being cross-browser and still perform efficiently?

6
  • 5
    Won't this return true on a string? Commented Jun 29, 2009 at 14:00
  • 1
    The example given is not ment to answer the question itself, is is merely an example of how a solution might be approached - which often fail in special cases (like this one, hence the "However, note..."). Commented Jun 29, 2009 at 14:45
  • 1
    cant' believe this is so difficult to do... Commented Jun 29, 2009 at 17:08
  • 2
    possible duplicate of How do you check if a variable is an array in JavaScript? Commented Oct 22, 2014 at 3:46
  • 1
    possible duplicate of Check if object is array? Commented Aug 7, 2015 at 7:23

12 Answers 12

173

Type checking of objects in JS is done via instanceof, ie

obj instanceof Array

This won't work if the object is passed across frame boundaries as each frame has its own Array object. You can work around this by checking the internal [[Class]] property of the object. To get it, use Object.prototype.toString() (this is guaranteed to work by ECMA-262):

Object.prototype.toString.call(obj) === '[object Array]'

Both methods will only work for actual arrays and not array-like objects like the arguments object or node lists. As all array-like objects must have a numeric length property, I'd check for these like this:

typeof obj !== 'undefined' && obj !== null && typeof obj.length === 'number'

Please note that strings will pass this check, which might lead to problems as IE doesn't allow access to a string's characters by index. Therefore, you might want to change typeof obj !== 'undefined' to typeof obj === 'object' to exclude primitives and host objects with types distinct from 'object' alltogether. This will still let string objects pass, which would have to be excluded manually.

In most cases, what you actually want to know is whether you can iterate over the object via numeric indices. Therefore, it might be a good idea to check if the object has a property named 0 instead, which can be done via one of these checks:

typeof obj[0] !== 'undefined' // false negative for `obj[0] = undefined`
obj.hasOwnProperty('0') // exclude array-likes with inherited entries
'0' in Object(obj) // include array-likes with inherited entries

The cast to object is necessary to work correctly for array-like primitives (ie strings).

Here's the code for robust checks for JS arrays:

function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

and iterable (ie non-empty) array-like objects:

function isNonEmptyArrayLike(obj) {
    try { // don't bother with `typeof` - just access `length` and `catch`
        return obj.length > 0 && '0' in Object(obj);
    }
    catch(e) {
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

As of MS JS 5.6 (IE6?), the "instanceof" operator leaked a lot of memory when run against a COM object (ActiveXObject). Have not checked JS 5.7 or JS 5.8, but this may still hold true.
@James: interesting - I didn't know of this leak; anyway, there's an easy fix: in IE, only native JS objects have a hasOwnProperty method, so just prefix your instanceof with obj.hasOwnProperty && ; also, is this still an issue with IE7? my simple tests via task manager suggest that the memory got reclaimed after minimizing the browser...
@Christoph - Not sure about IE7, but IIRC this was not on the list of bugfixes for JS 5.7 or 5.8. We host the underlying JS engine on the server side in a service, so minimizing the UI is not applicable.
@James: minimizing the UI is just an easy way to trigger garbage collection and other cleanup code; not knowing your environment, I'm not sure if you have any way to do something equivalent; also, isPrototypeOf() seems to have the same problem as it's basically the same thing (search the prototype chain for a specific object) - could you confirm?
@TravisJ: see ECMA-262 5.1, section 15.2.4.2; internal class names are by convention upper case - see section 8.6.2
|
49

The arrival of ECMAScript 5th Edition gives us the most sure-fire method of testing if a variable is an array, Array.isArray():

Array.isArray([]); // true

While the accepted answer here will work across frames and windows for most browsers, it doesn't for Internet Explorer 7 and lower, because Object.prototype.toString called on an array from a different window will return [object Object], not [object Array]. IE 9 appears to have regressed to this behaviour also (see updated fix below).

If you want a solution that works across all browsers, you can use:

(function () {
    var toString = Object.prototype.toString,
        strArray = Array.toString(),
        jscript  = /*@cc_on @_jscript_version @*/ +0;

    // jscript will be 0 for browsers other than IE
    if (!jscript) {
        Array.isArray = Array.isArray || function (obj) {
            return toString.call(obj) == "[object Array]";
        }
    }
    else {
        Array.isArray = function (obj) {
            return "constructor" in obj && String(obj.constructor) == strArray;
        }
    }
})();

It's not entirely unbreakable, but it would only be broken by someone trying hard to break it. It works around the problems in IE7 and lower and IE9. The bug still exists in IE 10 PP2, but it might be fixed before release.

PS, if you're unsure about the solution then I recommend you test it to your hearts content and/or read the blog post. There are other potential solutions there if you're uncomfortable using conditional compilation.

9 Comments

The accepted answer does work fine in IE8+, but not in IE6,7
@Pumbaa80: You're right :-) IE8 fixes the problem for its own Object.prototype.toString, but testing an array created in an IE8 document mode that is passed to an IE7 or lower document mode, the problem persists. I had only tested this scenario and not the other way around. I've edited to apply this fix only to IE7 and lower.
WAAAAAAA, I hate IE. I totally forgot about the different "document modes", or "schizo modes", as I'm gonna call them.
While the ideas are great and it looks good, this does not work for me in IE9 with popup windows. It returns false for arrays created by the opener... Is there a IE9 compatbile solutions? (The problem seems to be that IE9 implemnets Array.isArray itself, which returns false for the given case, when it should not.
@Steffen: interesting, so the native implementation of isArray does not return true from arrays created in other document modes? I'll have to look into this when I get some time, but I think the best thing to do is file a bug on Connect so that it can be fixed in IE 10.
|
8

Crockford has two answers on page 106 of "The Good Parts." The first one checks the constructor, but will give false negatives across different frames or windows. Here's the second:

if (my_value && typeof my_value === 'object' &&
        typeof my_value.length === 'number' &&
        !(my_value.propertyIsEnumerable('length')) {
    // my_value is truly an array!
}

Crockford points out that this version will identify the arguments array as an array, even though it doesn't have any of the array methods.

His interesting discussion of the problem begins on page 105.

There is further interesting discussion (post-Good Parts) here which includes this proposal:

var isArray = function (o) {
    return (o instanceof Array) ||
        (Object.prototype.toString.apply(o) === '[object Array]');
};

All the discussion makes me never want to know whether or not something is an array.

2 Comments

this will break in IE for strings objects and excludes string primitives, which are array-like except in IE; checking [[Class]] is better if you want actual arrays; if you want array-likes objects, the check is imo too restrictive
@ Christoph--I added a bit more via an edit. Fascinating topic.
2

jQuery implements an isArray function, which suggests the best way to do this is

function isArray( obj ) {
    return toString.call(obj) === "[object Array]";
}

(snippet taken from jQuery v1.3.2 - slightly adjusted to make sense out of context)

3 Comments

They return false on IE (#2968). (From jquery source)
That comment in the jQuery source seems to refer to the isFunction function, not isArray
you should use Object.prototype.toString() - that's less likely to break
2

Stealing from the guru John Resig and jquery:

function isArray(array) {
    if ( toString.call(array) === "[object Array]") {
        return true;
    } else if ( typeof array.length === "number" ) {
        return true;
    }
    return false;
}

3 Comments

The second test would return true for a string as well: typeof "abc".length === "number" // true
Plus, I guess you should never hardcode type names, like "number". Try comparing it to the actual number instead, like typeof(obj) == typeof(42)
@mtod: why shouldn't type names be hardcoded? after all, the return values of typeof are standardized?
2

Why not just use

Array.isArray(variable)

it is the standard way to do this (thanks Karl)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

1 Comment

This works in Node.js and in the browsers too, not just CouchDB: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

What are you going to do with the value once you decide it is an array?

For example, if you intend to enumerate the contained values if it looks like an array OR if it is an object being used as a hash-table, then the following code gets what you want (this code stops when the closure function returns anything other than "undefined". Note that it does NOT iterate over COM containers or enumerations; that's left as an exercise for the reader):

function iteratei( o, closure )
{
    if( o != null && o.hasOwnProperty )
    {
        for( var ix in seq )
        {
            var ret = closure.call( this, ix, o[ix] );
            if( undefined !== ret )
                return ret;
        }
    }
    return undefined;
}

(Note: "o != null" tests for both null & undefined)

Examples of use:

// Find first element who's value equals "what" in an array
var b = iteratei( ["who", "what", "when" "where"],
    function( ix, v )
    {
        return v == "what" ? true : undefined;
    });

// Iterate over only this objects' properties, not the prototypes'
function iterateiOwnProperties( o, closure )
{
    return iteratei( o, function(ix,v)
    {
        if( o.hasOwnProperty(ix) )
        {
            return closure.call( this, ix, o[ix] );
        }
    })
}

5 Comments

although the answer might be interesting, it doesn't really have anything to do with the question (and btw: iterating over arrays via for..in is bad[tm])
@Christoph - Sure it does. There must be some reason for deciding if something is an Array: because you want to do something with the values. The most typical things (in my code, at least) are to map, filter, search, or otherwise transform the data in the array. The above function does exactly that: if the thing passed has elements that can be iterated over, then it iterates over them. If not, then it does nothing and harmlessly returns undefined.
@Christoph - Why is iterating over arrays with for..in bad[tm]? How else would you iterate over arrays and/or hashtables (objects)?
@James: for..in iterates over enumerable properties of objects; you shouldn't use it with arrays because: (1) it's slow; (2) it isn't guaranteed to preserve order; (3) it will include any user-defined property set in the object or any of its prototypes as ES3 doesn't include any way to set the DontEnum attribute; there might be other issues which have slipped my mind
@Christoph - On the other hand, using for(;;) won't work properly for sparse arrays and it won't iterate object properties. #3 is considered bad form for Object due to the reason you mention. On the other hand, you are SO right with regards to performance: for..in is ~36x slower than for(;;) on a 1M element array. Wow. Unfortunatally, not applicable to our main use case, which is iterating object properties (hashtables).
0

If you want cross-browser, you want jQuery.isArray.

Comments

0

On w3school there is an example that should be quite standard.

To check if a variable is an array they use something similar to this

function arrayCheck(obj) { 
    return obj && (obj.constructor==Array);
}

tested on Chrome, Firefox, Safari, ie7

8 Comments

using constructor for type checking is imo too brittle; use one of the suggested alternatives instead
why do you think so? About brittle?
@Kamarey: constructor is a regular DontEnum property of the prototype object; this might not be a problem for built-in types as long as nobody does anything stupid, but for user-defined types it easily can be; my advise: always use instanceof, which checks the prototype-chain and doesn't rely on properties which can be overwritten arbitrarily
Thanks, found another explanation here: thinkweb2.com/projects/prototype/…
This is not reliable, because the Array object itself can be over-written with a custom object.
|
-2

One of the best researched and discussed versions of this function can be found on the PHPJS site. You can link to packages or you can go to the function directly. I highly recommend the site for well constructed equivalents of PHP functions in JavaScript.

Comments

-2

Not enough reference equal of constructors. Sometime they have different references of constructor. So I use string representations of them.

function isArray(o) {
    return o.constructor.toString() === [].constructor.toString();
}

1 Comment

fooled by {constructor:{toString:function(){ return "function Array() { [native code] }"; }}}
-4

Replace Array.isArray(obj) by obj.constructor==Array

samples :

Array('44','55').constructor==Array return true (IE8 / Chrome)

'55'.constructor==Array return false (IE8 / Chrome)

1 Comment

Why would you replace to correct function with a horrible one?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.