2088

How do I check if a variable is an array in JavaScript?

if (variable.constructor == Array)
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Andy McCluggage
  • 37,618
  • 18
  • 59
  • 69
  • 3
    Checking for an object to be an array has some specific caveats... Peter's answer is the only one you should use. – aleemb Apr 20 '09 at 09:20
  • 1
    @Andy It seems that my answer is not the best. Maybe you should select a different answer as accepted? – Peter Smit Aug 07 '11 at 18:10
  • 2
    Good point Peter. I hadn't realised your answer was receiving comments like this. I think I have long since begun to use the JQuery.isArray function when checking for arrays, and interestingly that is implemented differently to any other answer given here. I have marked the popular answer as correct. – Andy McCluggage Aug 08 '11 at 14:27
  • 1
    Sorry that's wrong. I looked a little deeper and (as of version 1.6.2) JQuery still type checks using comparisons in the form.... toString.call(obj) === "[object Array]" – Andy McCluggage Aug 08 '11 at 14:43
  • For IE8 support I would do this `if ('push' in variable.__proto__)`, the quickest and maybe best way to check if some var is array. – thednp Jul 05 '15 at 22:02
  • http://jsben.ch/#/QgYAV - a benchmark of the most common ways – EscapeNetscape Oct 24 '16 at 17:33
  • http://stackoverflow.com/questions/4775722/check-if-object-is-array/34116242#34116242 – shinobi Apr 30 '17 at 15:21
  • 8
    "This question has been asked before" ... NO, that question got asked AFTER this one – Dexygen Nov 12 '17 at 00:47

26 Answers26

1975

There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.

variable.constructor === Array

This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.

If you are having issues with finding out if an objects property is an array, you must first check if the property is there.

variable.prop && variable.prop.constructor === Array

Some other ways are:

Array.isArray(variable)

Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

variable instanceof Array

This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!

So yet another update

Object.prototype.toString.call(variable) === '[object Array]';

This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.

Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.

Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.

user229044
  • 232,980
  • 40
  • 330
  • 338
jemiloii
  • 24,594
  • 7
  • 54
  • 83
  • 3
    To extend the given answer another [jsperf test here](http://jsperf.com/instanceof-array-vs-array-isarray/6) using feature testing (.push && .pop) which is way tha fastest and supported in all browsers (even old ones). The catch is that maybe an object has 'push' and 'pop' properties without being an array. Also note that when testing if is array with an object created (or passed) from another frame, most of the tests will fail (since the **Array** in given window is different than **Array** in frame window). Also there is a catch if an array is constructed via new Array or literaly as [..] – Nikos M. Dec 15 '14 at 11:26
  • Interesting, I will have to do some more browser test. Chrome 38 on centos 7 has the push && pop as 10% faster than constructor, however, chrome 39 on windows 8 has constructor as the fastest with no close comparison as constructor runs 70% faster than push && pop. I'll just wait for some more test to come in, thanks! – jemiloii Dec 17 '14 at 19:18
  • 11
    Note that if you're not sure if the variable is defined or if it could be null, be sure to do those checks first since those are the common values/objects that do not have a constructor. – Michael Scott Asato Cuthbert Jan 12 '15 at 02:50
  • 2
    I was just focusing on the array portion. You can easily have `variable && variable.constructor === Array` to make sure that the variable isn't null or undefined. – jemiloii Jan 12 '15 at 16:46
  • Adicional methods: `!!~variable.constructor.toString().indexOf('Array()')`, `variable.constructor.toString() == Array().constructor.toString()` (probably will be a tiny bit slow) and `Object.prototype.toString.call(variable) == '[object Array]'` – Ismael Miguel Mar 26 '15 at 11:56
  • 3
    variable.constructor is faster only for checking actual arrays. When checking random objects (and in real world this will be the case as this is why you use this function) it's faster to use instanceof. http://jsperf.com/check-if-variable-is-array – Dinu Sorin Mar 16 '16 at 17:57
  • Using Chrome 50.0.2657.0 on Centos 7, constructor is still faster for me. Also, constructor can be used on everything except undefined and null. You can simply do `variable && variable.constructor`. Also to note, `5 instanceof Number` does not work as expected. Instance of looks for the prototype, numbers do not have a prototype, unless you set one. Numbers do have constructors. – jemiloii Mar 16 '16 at 18:52
  • As another weird note, ` Object.prototype.toString.call(1) === '[object Number]';` is a thing. Javascript is quirky, so Numbers do have prototypes. Just `instanceof` does not use them. Which is weird because, its the sole purpose of it according to MDN... – jemiloii Mar 16 '16 at 19:29
  • 7
    NOTE: 'variable.constructor === Array' will throw EXCEPTION if variable is null but 'variable instanceof Array' not! – GorvGoyl Oct 05 '16 at 09:29
  • if you look, i did provide an example of `variable && variable.constructor === Array` – jemiloii Oct 05 '16 at 16:15
  • The `Array.isArray(variable)` did not even work for me. The first one did excellent! – awe Sep 20 '17 at 13:17
  • @awe what browser are you using this on? – jemiloii Sep 20 '17 at 15:20
  • 2
    According to the JSPerf you posted, `Array.isArray` is the fastest, not the slowest – Ferrybig Sep 25 '17 at 13:39
  • what browser and version are you on? For me, chrome/firefox, which I quickly tested, constructor is still the fastest, however, there was a noticeable improvement on string only arrays. The string only arrays are very fast. I will be running more tests. – jemiloii Sep 25 '17 at 15:54
  • 6
    As of Chrome 59 isArray() seems to be significantly faster, so much so I see no reason to not use isArray() in all situations. – Hedley Smith Oct 10 '17 at 09:06
  • 2
    The original question did not mention performance. Those micro optimizations will be insignificant for almost all use cases – Drenai Feb 15 '18 at 18:29
  • 1
    Some people enjoy providing additional information instead of the bare minimums :) – jemiloii Feb 17 '18 at 22:34
  • 3
    All your benchmarks are wrong - both because V8 (Chrome) changed JIT compilers and because your benchmarks aren't relevant. I recommend you check out mraleph's blog about performance and jsperf in particular. The JSPerf is like ICs do not exist and the morphism of a function isn't relevant to the compiler whereas in practice the performance characteristics are widely different depending on what the engine can prove. – Benjamin Gruenbaum Jul 06 '18 at 10:23
  • 1
    Namely, V8 can [inline the value `true`](https://github.com/v8/v8/blob/c31cf146bfba9c3d4c570327561ed14021f73cb4/src/builtins/builtins-array-gen.cc#L2886) if type analysis proves the value is an array. This is irrelevant though since the `instanceof` is optimized to the same path. Amusingly the `.constructor` comparison is slower. The whole point of `isArray` is cross-realms (arrays passed between frames and contexts) anyway. – Benjamin Gruenbaum Jul 06 '18 at 10:25
  • is `variable.constructor === Array` still the accepted answer as being the fastest/most-performant? or has `variable instanceof Array` or `Array.isArray(variable)` become more viable? -- asking as the answers/comments are quite old in certain places. Much appreciated :) – Andu Andrici May 21 '19 at 06:41
  • Just run the tests to see, only takes a moment. – jemiloii May 23 '19 at 16:33
  • @AnduAndrici Yeah, there was a good update to Array.isArray() on Chrome. The second fastest option now. Solid! – jemiloii May 23 '19 at 17:06
  • 2
    I'd like to second @AnduAndrici's question because it's no longer clear from the answer which solution here is the most efficient. – Bash Jul 17 '19 at 13:56
  • its is clear @SebastianGaweda, read the answer. `variable.constructor === Array` If that was no longer the case, I would have updated it and provided a reason to why I had updated. – jemiloii Jul 31 '19 at 00:26
  • 4
    @jemiloii I disagree about it being clear. Your updates say that `instanceof` runs 2/3 the speed of the original answer. Does that mean faster? Slower? There's some ambiguity to the wording, although admittedly the context of the paragraph seems to indicate slower. I ran some benchmarks of my own by modifying the code in http://jsben.ch/QgYAV but those results suggested `instanceof` was fastest. On a related note, http://jsben.ch/QgYAV now links to an empty benchmark. – Bash Jul 31 '19 at 14:37
  • 4
    If you're gonna edit your answer, please consider making it more readable for those who have not read it before. – AtilioA Jun 11 '20 at 15:31
  • Javascript `instanceof` does not check for `undefined` and throws error when undefined :') would be worth mentioning – jave.web Mar 13 '22 at 14:02
  • @jemiloii I think now `variable.constructor === Array` will not work right!, we need to use `variable.constructor.name == "Array"` correct? – SHUBHAM DEKATE Mar 16 '23 at 04:39
1160

You could also use:

if (value instanceof Array) {
  alert('value is Array!');
} else {
  alert('Not an array');
}

This seems to me a pretty elegant solution, but to each his own.

Edit:

As of ES5 there is now also:

Array.isArray(value);

But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).

user229044
  • 232,980
  • 40
  • 330
  • 338
Brett Bender
  • 19,388
  • 2
  • 38
  • 46
  • 27
    I suggest, actually insist on sticking with this "instanceof" operator if you are not working with multiple frames. This is the right way of checking the object type. – BYK Apr 20 '09 at 09:21
  • 44
    The one case where this would fail is if you were trying to test for an Array or Object since `Array instanceof Object == true`. – Pierre Nov 28 '12 at 22:33
  • 1
    If you are using jQuery to pass elements with find('code') or something similar you would want to check the variable with `variable instanceof Object` since it is not an instance of an Array. – tuck May 01 '13 at 15:12
  • 1
    To reinforce @BYK's point, this only works with objects in the same frame. Don't rely on this if you are working with multiple frames! – Cory Klein Sep 25 '13 at 15:08
  • 1
    Doesn't work in some cases: `Array.prototype instanceof Array; // false` (should be true); also `({ __proto__ : Array.prototype }) instanceof Array; // true` (should be false) – vortexwolf Nov 04 '13 at 18:15
  • I'm not well-versed in JS internals - is the type of a prototype supposed to be the same as the type of the object? – Brett Bender Nov 04 '13 at 19:30
  • 5
    @BrettBender If you're still active, might you update your answer to reflect that as of ES5 we have Array.isArray? – Nobbynob Littlun May 22 '14 at 03:19
  • 5
    @AndrewK see [Fela Winkelmolen's answer](http://stackoverflow.com/a/20989617/3802811), which has the Array.isArray method. As for this answer, it's probably not a great idea to morph an answer into a different answer via editing. – muffin Aug 24 '14 at 20:45
  • Or if you don't care about old browsers you can use `Array.isArray(arr)` – Dominic Oct 13 '14 at 17:11
  • This is nice, but use variable.constructor === Array, by far the fastest method in javascript. http://jsperf.com/instanceof-array-vs-array-isarray – jemiloii Oct 29 '14 at 14:48
  • 1
    @muffin: why is it a good idea instead to let the answer stay outdated by five years? As you know, a lot of users won't read the comments under the answer (as much as we'd like them to), let alone that some of those comments are hidden under "Show more". – Dan Dascalescu Dec 04 '14 at 02:01
  • @DanDascalescu You're right that it's not good to keep valuable information buried. But I think it's inappropriate to alter someone's answer to the point where it no longer remains the same answer in essence. Perhaps adding a notice/FYI line edited into the top-voted answer would be helpful in a way that does not betray the integrity of the original answer, but if that's the indicated remedy the system ought to incorporate it on the same level as voting on and accepting answers. Anyway, I no longer peruse meta: I don't remember what (my sense of) the consensus is regarding answer integrity. – muffin Dec 04 '14 at 06:31
  • 1
    This is correct as it will handle if value is undefined or null as well. – James Nurse Aug 12 '15 at 12:31
85

In modern browsers (and some legacy browsers), you can do

Array.isArray(obj)

(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)

If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following

# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj)

If you don't need to detect arrays created in different frames you can also just use instanceof

obj instanceof Array

Note: the arguments keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:

var func = function() {
  console.log(arguments)        // [1, 2, 3]
  console.log(arguments.length) // 3
  console.log(Array.isArray(arguments)) // false !!!
  console.log(arguments.slice)  // undefined (Array.prototype methods not available)
  console.log([3,4,5].slice)    // function slice() { [native code] } 
}
func(1, 2, 3)
mitesh7172
  • 666
  • 1
  • 11
  • 21
Fela
  • 26,730
  • 8
  • 26
  • 24
  • 3
    This is probably the best most modern approach. I've seen it along with the polyfill on MDN so that means Mozilla trusts it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray – John Apr 12 '14 at 00:13
  • Aren't you missing `prototype` there? Seems it should be `Object.prototype.toString.call`. – Brock Nov 20 '14 at 11:16
  • we can also determine if the objects has the methods that are existing in array like push, splice, etc – aj go Jun 13 '22 at 07:58
82

There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Peter Smit
  • 27,696
  • 33
  • 111
  • 170
  • If you read carefully, it says this method is needed when you are working with mult-frame documents which, is not recommended. This method can easly borke on a little change in the "toString" function. – BYK Apr 20 '09 at 09:20
  • 4
    Therefor the link is given so that Brett can check them out and see in which case his function has to work – Peter Smit Apr 20 '09 at 09:23
  • 1
    See my answer below. I recommend Peter Smit's way. – Brian Jun 29 '12 at 19:28
  • 6
    This method is [recommended by Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). – Hank May 28 '15 at 15:52
76

I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.

jQuery implements it as Peter suggests:

isArray: function( obj ) {
    return toString.call(obj) === "[object Array]";
},

Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.

Many thanks for the suggestions.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
Andy McCluggage
  • 37,618
  • 18
  • 59
  • 69
  • See [this article](http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/) for a good discussion on the topic. The conclusion is to use this solution. – Nick G. Mar 12 '14 at 17:53
  • 1
    This gives me the error SCRIPT65535 in IE10. – polm23 May 27 '14 at 09:21
55

This is an old question but having the same problem i found a very elegant solution that i want to share.

Adding a prototype to Array makes it very simple

Array.prototype.isArray = true;

Now once if you have an object you want to test to see if its an array all you need is to check for the new property

var box = doSomething();

if (box.isArray) {
    // do something
}

isArray is only available if its an array

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • this sounds so cool to me! this could be native. btw it works even when a array was created before the prototyping? – Vitim.us Nov 12 '11 at 03:39
  • 5
    @Vitimtk A prototype acts as a fallback for the actual object, so this should work even if the array in question already existed. It won't work before the source line is processed, of course. – Markus Bruckner Dec 28 '11 at 19:39
  • 38
    Assuming no one does `Object.prototype.isArray = true;`! :( – ErikE Sep 30 '12 at 03:08
  • 14
    Note that in ES5 `Array.isArray` is a method (e.g., `Array.isArray([1,2,3]) === true`) so @ErikE wasn't being a troll. I would avoid following this answer as it will break code in some modern browsers. – JaredMcAteer Jul 11 '13 at 14:00
  • @JaredMcAteer your example is correct. However ErikE it is not related, Array != [1,2,3] . So you can still do [1,2,3].isArray === true with my solution – Ibu Jul 11 '13 at 19:19
  • 4
    @Ibu and you can do `{}.isArray === true` with my "solution", which was the whole point... – ErikE Jul 12 '13 at 04:47
  • 2
    Modifying the prototype of Data Types is a bad practice in my opinion – BentOnCoding Sep 24 '14 at 04:21
  • @BentOnCoding what about `Array.prototype["com.my.unique.name"].isArray` ;) – SOFe Dec 28 '18 at 04:49
48

Via Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window. That page has a much more sophisticated version if this is insufficient.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
35

If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function

e.g.,

Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
30

I personally like Peter's suggestion: https://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())

Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:

//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')
    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    }
    else
    {
        // may want to change return value to something more desirable
        return -1; 
    }
}

Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.

Community
  • 1
  • 1
Brian
  • 1,571
  • 1
  • 15
  • 20
  • 1
    Good call on the ECMAScript 5 standard. Sure you can't guarantee the browser supports it but this should be the first way to check in new code. – styfle Dec 13 '12 at 22:43
  • I'll start by saying that this is a bit over my head. However, would a test like this be more robust?: `return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);` – Grant Lindsay Jun 24 '14 at 12:41
20

When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.

Since JQuery now does offer this function, I would always use it...

$.isArray(obj);

(as of version 1.6.2) It is still implemented using comparisons on strings in the form

toString.call(obj) === "[object Array]"
Andy McCluggage
  • 37,618
  • 18
  • 59
  • 69
16

Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).

_.isArray(object) 

Returns true if object is an Array.

Sridhar
  • 11,466
  • 5
  • 39
  • 43
Benjen
  • 2,835
  • 5
  • 28
  • 42
10

If you are using Angular, you can use the angular.isArray() function

var myArray = [];
angular.isArray(myArray); // returns true

var myObj = {};
angular.isArray(myObj); //returns false

http://docs.angularjs.org/api/ng/function/angular.isArray

  • 1
    You can also use non Angular specific, but only IE9+ and all standards browsers:
    
        Array.isArray(myArray); //returns true
        Array.isArray(myObj); //returns false
    
    
    – PDA Jul 17 '14 at 16:08
8

In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

He explains:

First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.

Yunzhou
  • 593
  • 6
  • 13
5

The universal solution is below:

Object.prototype.toString.call(obj)=='[object Array]'

Starting from ECMAScript 5, a formal solution is :

Array.isArray(arr)

Also, for old JavaScript libs, you can find below solution although it's not accurate enough:

var is_array = function (value) {
    return value &&
    typeof value === 'object' &&
    typeof value.length === 'number' &&
    typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript

PixelsTech
  • 3,229
  • 1
  • 33
  • 33
3

For those who code-golf, an unreliable test with fewest characters:

function isArray(a) {
  return a.map;
}

This is commonly used when traversing/flattening a hierarchy:

function golf(a) {
  return a.map?[].concat.apply([],a.map(golf)):a;
}

input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
000
  • 26,951
  • 10
  • 71
  • 101
2

code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js

  var isArray = Array.isArray || function(obj) {
    return !!(obj && obj.concat && obj.unshift && !obj.callee);};
didxga
  • 5,935
  • 4
  • 43
  • 58
  • Why do you test both `concat` and `unshift`, wouldn't suffice to test for `unshift`? – Marco Demaio Feb 18 '14 at 14:55
  • The more methods we check that Array has the move likely it really is an array. Other objects might have `concat` or `unshift` but less likely to have both. – Kris Apr 24 '14 at 13:35
1

I was using this line of code:

if (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
  • 8
    This is not a good solution at all. With this "solution" any object with a property `push` that is truthy will be considered an Array. – teleclimber Apr 28 '14 at 17:41
1

I have created this little bit of code, which can return true types.

I am not sure about performance yet, but it's an attempt to properly identify the typeof.

https://github.com/valtido/better-typeOf also blogged a little about it here http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/

it works, similar to the current typeof.

var user = [1,2,3]
typeOf(user); //[object Array]

It think it may need a bit of fine tuning, and take into account things, I have not come across or test it properly. so further improvements are welcomed, whether it's performance wise, or incorrectly re-porting of typeOf.

Val
  • 17,336
  • 23
  • 95
  • 144
1

I think using myObj.constructor==Object and myArray.constructor==Array is the best way. Its almost 20x faster than using toString(). If you extend objects with your own constructors and want those creations to be considered "objects" as well than this doesn't work, but otherwise its way faster. typeof is just as fast as the constructor method but typeof []=='object' returns true which will often be undesirable. http://jsperf.com/constructor-vs-tostring

one thing to note is that null.constructor will throw an error so if you might be checking for null values you will have to first do if(testThing!==null){}

user1585789
  • 648
  • 6
  • 14
1

From w3schools:

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
Jahid
  • 21,542
  • 10
  • 90
  • 108
0

I liked the Brian answer:

function is_array(o){
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    } else{
        // may want to change return value to something more desirable
        return -1; 
    }
}

but you could just do like this:

return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
zeageorge
  • 9
  • 1
  • 2
0

I tried most of the solutions here. But none of them worked. Then I came up with a simple solution. Hope it will help someone & save their time.

if(variable.constructor != undefined && variable.constructor.length > 0) {
        /// IT IS AN ARRAY
} else {
       /// IT IS NOT AN ARRAY
}
Ujjwal Raijada
  • 867
  • 10
  • 21
0

Here is an answer that works without fail both in old browsers and across frames. It takes the recommended Array.isArray() static method of EcmaScript 5+ and the old recommended way before ES5 and combines them so that you have a working function in both new and old JS versions:

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

isArray([]);//true

Of course Array.isArray() is more than 10 years old now. So you might not need to support browsers older than that. However you shouldn't underestimate the number of old browsers that are still out there.

PHP Guru
  • 1,301
  • 11
  • 20
0
 if(elem.length == undefined){
    // is not an array
 }else{
    // is an array
 } 
-7

Since the .length property is special for arrays in javascript you can simply say

obj.length === +obj.length // true if obj is an array

Underscorejs and several other libraries use this short and simple trick.

TypingTurtle
  • 156
  • 9
  • 1
    Would you mind explaining how that works? Mainly, what does the '+' do? – Andy McCluggage Mar 03 '14 at 14:21
  • 1
    This is good, but it is also true when the object is a function or a string as well as any other object with property length of type number. Why? Well, the unary + operator actually casts a variable as a number. So basically they are checking if obj.length is a number. [object Object] has no property length it is undefined so when you cast undefined as a number it becomes NaN the above check comes out as false. So it returns true if the object property length is a number, which in the case of arrays, strings, and functions it would be true. Underscore has to be doing more than just this. – John Apr 12 '14 at 00:36
-22

Something I just came up with:

if (item.length) //This is an array else //not an array

trololol
  • 25
  • 7