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;
}
}
The best way is probably to use the standard Array.isArray()
, if it's implemented by the engine:
isArray = Array.isArray(myObject)
MDN recommends to use the toString()
method when Array.isArray
isn't implemented:
Compatibility
Running the following code before any other code will create
Array.isArray if it's not natively available. This relies on
Object.prototype.toString being unchanged and call resolving to the
native Function.prototype.call method.
if(!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == '[object Array]';
};
}
Both jQuery and underscore.js[source] take the toString() === "[object Array]"
way.
Best Answer
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.
This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.
If you are having issues with finding out if an objects property is an array, you must first check if the property is there.
Some other ways are:
Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question This last one is, in my opinion the ugliest, and it is one of the
slowestfastest.Running about 1/5 the speed as the first example.This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArrayThis method runs about
1/3 the speedas the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work asvariable instanceof Number
always returnsfalse
. Update:instanceof
now goes 2/3 the speed!So yet another update
This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.
Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.
Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.