Alex Rivera | Logout

How do I check if a variable is an array in JavaScript?

Asked 2009-04-20T09:02:59.553
2184

How do I check if a variable is an array in JavaScript?

if (variable.constructor == Array)
Edit
Report

2 Answers

83

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

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}
answered 2009-04-20T09:08:08.263
55

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

answered 2011-10-24T21:12:50.357

Your Answer