6

Is it correct to use obj.constructor === Array to test if an object is an array as suggested here? Does it always returns correct answer compatible with Array.isArray?

Community
  • 1
  • 1
Ali Shakiba
  • 20,549
  • 18
  • 61
  • 88
  • you can also use the boolean return from "obj instanceof Array", but like your version, it only returns true for an Array of the same window scope. – kennebec Feb 12 '15 at 01:03
  • Do you have read any of the other answers on that question? http://blog.niftysnippets.org/2010/09/say-what.html – Bergi Apr 01 '15 at 20:08
  • @Bergi Yes, when I asked this question I was interested to learn more about `obj.constructor === Class` as well. – Ali Shakiba Apr 01 '15 at 20:14

1 Answers1

11

Depends, there are a few scenarios where it can return a different value, but Array.isArray will work.

The Array object for one window is not the the same Array object in another window.

var obj = someIframe.contentWindow.someArray;
console.log(obj.constructor === Array);//false
console.log(Array.isArray(obj));//true

The constructor property can be overwritten.

var obj = [];
obj.constructor = null;
console.log(obj.constructor === Array);//false
console.log(Array.isArray(obj));//true

Another object can also set the constructor property to Array.

var obj = {};
obj.constructor = Array;
console.log(obj.constructor === Array);//true
console.log(Array.isArray(obj));//false
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171