Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to check whether a variable is either an array or a single value in JavaScript.

I have found a possible solution...

if (variable.constructor == Array)...

Is this the best way this can be done?

share|improve this question
1  
Checking for an object to be an array has some specific caveats... Peter's answer is the only one you should use. – aleemb Apr 20 '09 at 9:20
@Andy It seems that my answer is not the best. Maybe you should select a different answer as accepted? – Peter Smit Aug 7 '11 at 18:10
Good point Peter. I hadn't realised your answer was receiving comments like this. I think I have long since begun to use the JQuery.isArray function when checking for arrays, and interestingly that is implemented differently to any other answer given here. I have marked the popular answer as correct. – Andy McCluggage Aug 8 '11 at 14:27
1  
Sorry that's wrong. I looked a little deeper and (as of version 1.6.2) JQuery still type checks using comparisons in the form.... toString.call(obj) === "[object Array]" – Andy McCluggage Aug 8 '11 at 14:43
add comment (requires an account with 50 reputation)

13 Answers

up vote 306 down vote accepted

You could also use:

if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}

This seems to me a pretty elegant solution, but to each his own.

share|improve this answer
9  
I suggest, actually insist on sticking with this "instanceof" operator if you are not working with multiple frames. This is the right way of checking the object type. – BYK Apr 20 '09 at 9:21
4  
The one case where this would fail is if you were trying to test for an Array or Object since Array instanceof Object == true. – Pierre Nov 28 '12 at 22:33
If you are using jQuery to pass elements with find('code') or something similar you would want to check the variable with variable instanceof Object since it is not an instance of an Array. – tuck May 1 at 15:12
add comment (requires an account with 50 reputation)

If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function

e.g.,

Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false
share|improve this answer
add comment (requires an account with 50 reputation)

I liked the Brian answer:

function is_array(o){
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    } else{
        // may want to change return value to something more desirable
        return -1; 
    }
}

but you could just do like this:

return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
share|improve this answer
add comment (requires an account with 50 reputation)
function isArray(x){
    return (typeof x.push != "undefined");
}
share|improve this answer
add comment (requires an account with 50 reputation)

I was using this line of code:

if (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}
share|improve this answer
add comment (requires an account with 50 reputation)

I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.

jQuery implements it as Peter suggests:

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

Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.

Many thanks for the suggestions.

share|improve this answer
add comment (requires an account with 50 reputation)

There are multiple solutions with all their on quirks. This page gives a good overview. One possible solution is:

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}
share|improve this answer
7  
Come on, that method is so, well, unappropriate. – BYK Apr 20 '09 at 9:16
If you read carefully, it says this method is needed when you are working with mult-frame documents which, is not recommended. This method can easly borke on a little change in the "toString" function. – BYK Apr 20 '09 at 9:20
3  
Therefor the link is given so that Brett can check them out and see in which case his function has to work – Peter Smit Apr 20 '09 at 9:23
But when you read your answer, it looks like that method is the best, overall. This is why I warned ;) – BYK Apr 20 '09 at 13:56
1  
@icCube Please, tell why it is not the way to go! – Peter Smit Aug 8 '11 at 3:08
show 2 more commentsadd comment (requires an account with 50 reputation)

I personally like Peter's suggestion: http://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())

Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:

//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')
    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    }
    else
    {
        // may want to change return value to something more desirable
        return -1; 
    }
}

Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.

share|improve this answer
Good call on the ECMAScript 5 standard. Sure you can't guarantee the browser supports it but this should be the first way to check in new code. – styfle Dec 13 '12 at 22:43
add comment (requires an account with 50 reputation)

Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://documentcloud.github.com/underscore/#isArray).

_.isArray(object) 

Returns true if object is an Array.

share|improve this answer
add comment (requires an account with 50 reputation)

This is an old question but having the same problem i found a very elegant solution that i want to share.

Adding a prototype to Array makes it very simple

Array.prototype.isArray = true;

Now once if you have an object you want to test to see if its an array all you need is to check for the new property

var box = doSomething();

if (box.isArray) {
    // do something
}

isArray is only available if its an array

share|improve this answer
this sounds so cool to me! this could be native. btw it works even when a array was created before the prototyping? – Vitim.us Nov 12 '11 at 3:39
3  
@Vitimtk A prototype acts as a fallback for the actual object, so this should work even if the array in question already existed. It won't work before the source line is processed, of course. – Markus Bruckner Dec 28 '11 at 19:39
10  
Assuming no one does Object.prototype.isArray = true;! :( – ErikE Sep 30 '12 at 3:08
2  
@ErikE that made me lol. this.trollcode = true – destiel starship Nov 18 '12 at 13:44
2  
Genius. +1 to your awesomeness :) – Jashwant Mar 13 at 7:19
show 5 more commentsadd comment (requires an account with 50 reputation)

When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.

Since JQuery now does offer this function, I would always use it...

$.isArray(obj);

(as of version 1.6.2) It is still implemented using comparisons on strings in the form

toString.call(obj) === "[object Array]"
share|improve this answer
add comment (requires an account with 50 reputation)

code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js

  var isArray = Array.isArray || function(obj) {
    return !!(obj && obj.concat && obj.unshift && !obj.callee);};
share|improve this answer
add comment (requires an account with 50 reputation)

Via Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window. That page has a much more sophisticated version if this is insufficient.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.