JavaScript – Best Way to Check if an Object is an Array

javascript

As far as I know there are three ways of finding out if an object is an Array

by isArray function if implemented

Array.isArray()

by toString

Object.prototype.toString.apply( obj ) === "[object Array]"

and by instanceof

obj instanceof Array

Is there any reason to choose one over the other?

Best Answer

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.

Related Question