Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is instanceof Array better than isArray in JavaScript?

From those two posts:

  • How do you check if a variable is an array in JavaScript?
  • Check if object is array?

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?

like image 937
zangw Avatar asked Feb 28 '15 07:02

zangw


1 Answers

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.

like image 115
levi Avatar answered Sep 20 '22 01:09

levi