This question already has an answer here:
I want to check a variable is it array?
which is the best method used for this to get better performance.
isArray
or
instanceof
This question already has an answer here:
I want to check a variable is it array?
which is the best method used for this to get better performance.
isArray
or
instanceof
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.
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.