Testing if the element is an array, in Javascript

To check if an element is an array in JavaScript, I have always used Crockford's function (pg 61 of The Good Parts):

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&

But if I'm not mistaken, recently some guy from Google had found a new way on how to test for a JavaScript array, but I just can't remember from where I read it and how the function went.

Can anyone point me to his solution please?

[Update] The person from Google who apparently discovered this is called Mark Miller.

Now I've also read that from this post that his solution can easily break as well:

// native prototype overloaded, some js libraries extends them
Object.prototype.toString= function(){
  return  '[object Array]';

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

var a = {};
alert(isArray(a)); // returns true, expecting false;

So, I ask, is there any way that we can truly check for array validity?


I believe you are looking for

Object.prototype.toString.call(value) === "[object Array]";

This is the method that jQuery uses to check whether a passed parameter value is a function or array object. There are browser specific instances where using typeof does not yield the correct result

You could do this:

t = [1,2];
// Now to check if this is an array
if (t.constructor == Array)
    alert('t is an array');
    alert('t is NOT an array');

Basically, variable.constructor == Array

Need Your Help

Displaying map in a Fragment

android android-layout android-fragments android-maps-v2

I have a master class which creates two fragment classes. One of them is MapDisplay().java

Setting QTextDocument painter's rectangle (where to paint)

html qt qtextdocument

I am painting on a window simple html using QTextDocument::drawContents(painter)