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
3
  • 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. Commented Aug 7, 2015 at 6:02
  • FWIW, these all correctly yield false on the special arguments object defined inside a function. Commented Aug 7, 2015 at 6:12
  • Or, the literal duplicate: Whats the best way to find out if an Object is an Array Commented Aug 7, 2015 at 7:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.