111

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?

stpe
  • 3,611
  • 3
  • 31
  • 38
  • 5
    Won't this return true on a string? – James Hugard Jun 29 '09 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..."). – stpe Jun 29 '09 at 14:45
  • @James: in most browsers (IE excluded), strings are array-like (ie access via numerical indices is possible) – Christoph Jun 29 '09 at 15:50
  • 1
    cant' believe this is so difficult to do... – Claudiu Jun 29 '09 at 17:08
  • 2
    possible duplicate of [How do you check if a variable is an array in JavaScript?](http://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript) – Foreever Oct 22 '14 at 03:46
  • 1
    possible duplicate of [Check if object is array?](http://stackoverflow.com/q/4775722/1048572) – Bergi Aug 07 '15 at 07:23

12 Answers12

171

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;
    }
}
Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 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 Hugard Jun 29 '09 at 17:42
  • 1
    @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 Jun 29 '09 at 18:32
  • @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 Hugard Jun 29 '09 at 18:43
  • @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? – Christoph Jun 29 '09 at 18:57
  • Can't duplicate the leak with JS 5.6 on Win2003 w/IE7 (was discovered on Win2000 w/IE6), but ignore at your own peril :P – James Hugard Jun 30 '09 at 04:07
  • @Christoph - Will different browsers return different values, such as `[object array]`? Or if checking for an object, `[object object]`? Or is this standardized? – Travis J Oct 24 '12 at 20:52
  • 1
    @TravisJ: see [ECMA-262 5.1, section 15.2.4.2](http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2); internal class names are by convention upper case - see [section 8.6.2](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6.2) – Christoph Oct 24 '12 at 22:56
  • "This won't work if the object is passed across frame boundaries as each frame has its own Array object." By Array object you mean window.Array, which is actually a function/object constructor right? – Hoffmann Dec 11 '12 at 17:00
  • @Hoffmann: correct; in general, `window1.Array !== window2.Array` which means `window1.Array.prototype !== window2.Array.prototype` and thus `new window1.Array instanceof window2.Array === false` – Christoph Dec 13 '12 at 10:28
  • Interesting, so in some rather bizarre circumstances you would actually want to differentiate both objects. For example when you augmented the array prototype in one frame but not in the other. – Hoffmann Dec 13 '12 at 12:05
  • don't use the `[0]`-checking solution, you may define a "hybrid" object that has the 0 as an attribute (but is NOT an Array): `var a = {0:"hi",b:"aa"};` and then you may run: `typeof a[0]` - and actually getting: `"hi"` (so.. not "undefine"). I am using (a bit of overkill..) this one: `var type = typeof something; "object" === type ? (something instanceof Array || "[object Array]" === Object.prototype.toString.call(something) ? "array" : type) : type;`. –  Jan 09 '15 at 23:54
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.

Joorren
  • 103
  • 1
  • 5
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • [The accepted answer](http://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array/1058753#1058753) does work fine in IE8+, but not in IE6,7 – user123444555621 Oct 27 '10 at 09:21
  • @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. – Andy E Oct 27 '10 at 09:47
  • WAAAAAAA, I hate IE. I totally forgot about the different "document modes", or "schizo modes", as I'm gonna call them. – user123444555621 Oct 27 '10 at 10:23
  • 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 Heil Jul 10 '11 at 07:48
  • @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. – Andy E Jul 10 '11 at 09:46
  • @Steffen: I've filed a bug on Connect and updated my post to work with all versions of IE. – Andy E Jul 10 '11 at 13:53
  • This works for me in IE9 now. Thanks. (Though, I replaced `"constructor" in obj` with `obj.constructor` which should be the same, right? I could not find information if all browsers support `in`...) – Steffen Heil Jul 11 '11 at 11:14
  • @Steffen: http://stackoverflow.com/questions/2920765/javascript-in-operator-compatibility/2920832#2920832 :-) – Andy E Jul 12 '11 at 23:28
  • Although this won't work under IE8 because of lack of `Array.isArray`, still +1 for @cc_on trick I didn't know :D – SOReader Oct 06 '14 at 12:08
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.

Nosredna
  • 83,000
  • 15
  • 95
  • 122
  • 1
    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 Jun 29 '09 at 15:23
  • @ Christoph--I added a bit more via an edit. Fascinating topic. – Nosredna Jun 29 '09 at 15:37
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)

Mario Menger
  • 5,862
  • 2
  • 28
  • 31
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;
}
razzed
  • 2,653
  • 25
  • 27
  • 2
    The second test would return true for a string as well: typeof "abc".length === "number" // true – Daniel Vandersluis Jun 29 '09 at 14:05
  • 2
    Plus, I guess you should never hardcode type names, like "number". Try comparing it to the actual number instead, like typeof(obj) == typeof(42) – ohnoes Jun 29 '09 at 14:29
  • 5
    @mtod: why shouldn't type names be hardcoded? after all, the return values of `typeof` are standardized? – Christoph Jun 29 '09 at 14:57
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

  • This works in Node.js and in the browsers too, not just CouchDB: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray – Karl Wilbur Oct 26 '18 at 19:01
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] );
        }
    })
}
James Hugard
  • 3,232
  • 1
  • 25
  • 36
  • 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 Jun 29 '09 at 15:49
  • @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. – James Hugard Jun 29 '09 at 17:29
  • @Christoph - Why is iterating over arrays with for..in bad[tm]? How else would you iterate over arrays and/or hashtables (objects)? – James Hugard Jun 29 '09 at 17:29
  • 1
    @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 Jun 29 '09 at 18:46
  • 1
    @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). – James Hugard Jun 29 '09 at 19:58
0

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

Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79
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

Eineki
  • 14,773
  • 6
  • 50
  • 59
  • using `constructor` for type checking is imo too brittle; use one of the suggested alternatives instead – Christoph Jun 29 '09 at 14:52
  • why do you think so? About brittle? – Kamarey Jun 29 '09 at 15:19
  • @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 – Christoph Jun 29 '09 at 15:32
  • 1
    Thanks, found another explanation here: http://thinkweb2.com/projects/prototype/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ – Kamarey Jun 29 '09 at 15:39
  • This is not reliable, because the Array object itself can be over-written with a custom object. – Josh Stodola Jun 29 '09 at 17:26
  • @Christoph - the problem with "instanceof" is that it leaks (big time) when run against COM objects in IE. – James Hugard Jun 29 '09 at 17:31
  • @Josh: but overwriting `window.Array` is almost always stupid, whereas replacing prototypes of non-native objects isn't; so instead of using `constructor` for natives and `instanceof` otherwise, why not always use `instanceof` (memory issues aside)? – Christoph Jun 29 '09 at 19:02
  • @Kamarey, link is now broken, thinkweb2.com doesn't resolve. Removing the 2 just gets you a 404 from thinkweb.com. – Michael Blackburn Jan 17 '14 at 15:15
-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.

Tony Miller
  • 9,059
  • 2
  • 27
  • 46
-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();
}
kuy
  • 944
  • 5
  • 12
  • fooled by `{constructor:{toString:function(){ return "function Array() { [native code] }"; }}}` – Bergi Aug 07 '15 at 07:14
-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)