8

From those two posts:

There are several ways to check if one object is an array

  1. variable instanceof Array

  2. Array.isArray(variable)

I was told that the second method is better than the first one. Is anyone can tell the reason of it?

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214
  • the 2nd one is not available in older browsers, but where it is available, hits Arrays from iframes that instanceOf misses. – dandavis Feb 28 '15 at 09:04

1 Answers1

12

No. There are some cases where obj instanceof Array can be false, even if obj is an Array.

You do have to be careful with instanceof in some edge cases, though, particularly if you're writing a library and so have less control / knowledge of the environment in which it will be running. The issue is that if you're working in a multiple-window environment (frames, iframes), you might receive a Date d (for instance) from another window, in which case d instanceof Date will be false — because d's prototype is the Date.prototype in the other window, not the Date.prototype in the window where your code is running. And in most cases you don't care, you just want to know whether it has all the Date stuff on it so you can use it.

Source: Nifty Snippets

This example, applies to array objects too and so on.

And the standard method suggest by ECMAScript standards to find the class of an Object is to use the toString method from Object.prototype and isArray(variable) uses it internally.

Daniel Baird
  • 2,239
  • 1
  • 18
  • 24
levi
  • 22,001
  • 7
  • 73
  • 74