3

What is the best way to determining the object type is Array and why?.

var arr = [];

// Method #1
Array.isArray(arr);

// Method #2 
toString.call(arr) == "[object Array]"

// Method #3
arr.constructor == Array
dfsq
  • 191,768
  • 25
  • 236
  • 258
venkat7668
  • 2,657
  • 1
  • 22
  • 26
  • 2
    It seems obvious to me that the best way would be to use the function built exactly for that purpose - namely `Array.isArray`. I can't see how either of the other ways could be better but maybe someone can prove me wrong. – Maximillian Laumeister Aug 07 '15 at 06:02
  • FWIW, these all correctly yield `false` on the special `arguments` object defined inside a function. – Paul Aug 07 '15 at 06:12
  • Or, the literal duplicate: [Whats the best way to find out if an Object is an Array](http://stackoverflow.com/q/7447425/1048572) – Bergi Aug 07 '15 at 07:08

2 Answers2

3

All three methods can be used to test if variable is of Array type. However, there are some nuances. I will start from the last to first.

Method #3. Will not work if variable in question came from other winndow/frame. In this case, constructor will point the the different Array object and this check will return false. For the same reason, arr instanceof Array is not bullet-proof. So it's not 100% reliable.

Method #2. This is the method that has been traditionally used to verify array type. In fact, Array.isArray polyfill is based on this method. The only disadvantage is that it's cumbersome and verbose.

Method #1. Is the one from ES5 that should finally be used to test array type, no matter what realm array comes from (like iframe). This is is the best in the list.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

The prefered method is to use Array.isArray. This is present in the ES5 language specification and quite well supported by the browsers.

If you plan to support old browsers, You can find a polyfill on MDN. The polyfill is basically your second option.

The last option will not work if you play with iframes.

var arr = myIframe.contentWindow.myArray;
console.log(obj.constructor === Array); //false

The reason is that the Array constructor is diffferent for each window object. Using this to detect arrays will work 99% of the time but will suddenly fail one day.

vmeurisse
  • 70
  • 5