2

I want to check a variable is it array?

which is the best method used for this to get better performance.

isArray

or

instanceof

Sergio
  • 28,539
  • 11
  • 85
  • 132
Md. Sahadat Hossain
  • 3,210
  • 4
  • 32
  • 55
  • Array.isArray would be the native way and probably the best if the browser supports it. – adeneo Oct 05 '13 at 10:13
  • In practically all cases any performance difference is minuscule, and in any case where the difference is meaningful you could just measure it yourself. – JJJ Oct 05 '13 at 10:15

2 Answers2

3

Big guys (Jquery, underscore) do it like this:

  isArray = Array.isArray || function(obj) {
    return Object.prototype.toString.call(obj) == '[object Array]';
  };

But these are not the droids you're looking for you actually don't need this at all. Don't "check" your variables - just know them.

georg
  • 211,518
  • 52
  • 313
  • 390
  • When you refer to the "big guys" you should also say that they are hoisting the toString method `var toString = Object.prototype.toString;`... An inside the function: `return toString.call(..` – Andreas Louv Oct 05 '13 at 10:24
2

Array.IsArray would be better to use.

Also check this instanceof considered harmful (or how to write a robust isArray)

The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

Also you can check the speed variation between the two and you will find that isArray is comparatively faster.

Here is a link to check that:- Array.isArray vs instanceof Array

Below code is used to check the speed variation:

<script>
  Benchmark.prototype.setup = function() {
    var a = [1, 2, 3];
    var s = 'example';
    var f = false;
  };
</script>

Using Array.IsArray:

(Array.isArray(a) && (Array.isArray(s) || Array.isArray(f)));

it performed nearly 25,255,693 ops/sec

Now using instanceof:-

 (a instanceof Array && (s instanceof Array || f instanceof Array));

it performed nearly 21,594,618 ops/sec

ie, instanceOf is 15% slower than using IsArray.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331