Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to find out if an Object is an Array

Tags:

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?

like image 321
NebulaFox Avatar asked Sep 16 '11 15:09

NebulaFox


Video Answer


2 Answers

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.

like image 98
Arnaud Le Blanc Avatar answered Sep 18 '22 06:09

Arnaud Le Blanc


Unless it was proven that the former has significant performance benefits and my app required every last ounce of speed I would go for the latter.

The reason is readability, pure and simple.

like image 23
Chris Simpson Avatar answered Sep 21 '22 06:09

Chris Simpson