I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error.

So how do I check if the variable is an array?


I've rounded up the various solutions below and created a jsperf test.

5 upvote
  flag
I thought you meant to 'check if object is an array', but you want to check if 'object is an array of strings or a single string' specifically. Not sure if you see it? Or is it just me? I was thinking of something more like this... am I the one missing something here? – rr1g0
94 upvote
  flag
TL;DR - arr.constructor === Array is fastest. – Neta
upvote
  flag
You had an important part of the screenshot cut, above the test, where it's written where did the test occur. My test is very different. – vsync
1 upvote
  flag
@vsync There's a hyperlink. You guys can run it as much as you like. The screenshot is there just for people that are too lazy to click. – mpen
3 upvote
  flag
jsben.ch/#/QgYAV - a benchmark for the most common ways – EscapeNetscape
upvote
  flag
@Neta and what about arr instanceof Array? – Ring Ø
1 upvote
  flag
@EscapeNetscape Your prototype test doesn't actually test anything. – mpen
17 upvote
  flag
TL;DR - Array.isArray(arr) since ES5; and $.isArray(arr) in jQuery. – Ondra Žižka
upvote
  flag
@sheelpriy > [].constructor === Array // true – Rodrigo Leite
upvote
  flag
how about just typeof x === "string" to see if it's a string, and if not you can assume it's an array for your use case – Chris Barr

36 Answers 11

The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
    alert( 'Array!' );
}

Or you could use typeof to test if it is a String:

if( typeof someVar === 'string' ) {
    someVar = [ someVar ];
}

Or if you're not concerned about performance, you could just do a concat to a new empty Array.

someVar = [].concat( someVar );

There's also the constructor which you can query directly:

if (somevar.constructor.name == "Array") {
    // do something
}

EDIT: Check out a thorough treatment from @T.J. Crowder's blog, as posted in his comment below.

EDIT 2: Check out this benchmark to get an idea which method performs better: http://jsben.ch/#/QgYAV

Edit 3: From @Bharath convert string to array using Es6 for the question asked:

const convertStringToArray = (object) => {
   return (typeof object === 'string') ? Array(object) : object 
}

suppose:

let m = 'bla'
let n = ['bla','Meow']
let y = convertStringToArray(m)
let z = convertStringToArray(n)
console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']
61 upvote
  flag
+1 Yup, toString is one of the ways to go. I do a bit of a roundup here: blog.niftysnippets.org/2010/09/say-what.html – T.J. Crowder
upvote
  flag
@T.J. Crowder: Looks good. Updating my answer with your blog post. – user113716
upvote
  flag
This works on Titanium too. – neoneye
3 upvote
  flag
typeof new String('beans') > 'object' – Ben
16 upvote
  flag
If you don't want to type "[object Array]" use Object.prototype.toString.call( someVar ) === Object.prototype.toString.call( [] ) or make a convenience function to get type if you don't want to type Object.prototype.toString.call – Pramod
14 upvote
  flag
Wow. The concat method is the one diseased rat. I'd give a +2 but that's not allowed – Dark Star1
9 upvote
  flag
I use the vanilla Array.isArray which works in 'modern browsers' (that is, IE9+ and everyone else). And for old browser support use the shim from MDN developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – David Gilbertson
upvote
  flag
Like a baws! function getType(_o){ try{ return Object.prototype.toString.call(_o).substring("[object ")[1].split("]")[0].toLowerCase()}catch(e){}} – Jakob Sternberg
upvote
  flag
It seems to me like the check for String is simpler than the check for Array...as long as you ignore the caveat about typeof not working with Strings created by new String('hello') – lmsurprenant
upvote
  flag
Is there any reason one wouldn't use the shorter syntax if( someVar.toString() === "[object Object]") { ... } ? – Greg
upvote
  flag
I needed that for the last question of this game games.usvsth3m.com/javascript-under-pressure : ) – Pavel Nikolov
upvote
  flag
@DarkStar1—yes, diseased:[].concat( [] ) returns an empty array, as does undefined and null, so as a test it will rate them all the same. – RobG
upvote
  flag
RobG: I don't think the concat() example was meant to be a generalized test. Looks like it's tailored for the specific problem described in the question. – cookie monster
upvote
  flag
I prototyped it so i can use it anaywhere: Object.prototype.isArray = function () { if(Object.prototype.toString.call(this) == '[object Array]') { return true; } return false; }; – Freddy
upvote
  flag
What browser support does this offer? – user2330270
upvote
  flag
@Ben That's not a string; it's a String object. – JLRishe
upvote
  flag
@Greg Not all objects inherit prototype. try for instance var a = Object.create(null); a.toString(); -> gives uncaught TypeError. //allinonescript.com/questions/4166616/… – jonas
upvote
  flag
note that the summarized question "check if object is array" is better addressed by using Array.isArray() or jquery's isArray, as mentioned in Fela's answer below. – Patrick Finnigan
upvote
  flag
@PatrickFinnigan: I don't think too many browsers supported Array.isArray in Jan. 2011 but it's really just a shorthand for the .toString.call... version. They're exactly equivalent. es5.github.io/#x15.4.3.2 And jQuery definitely isn't needed. – Lye Fish
upvote
  flag
@LyeFish Sure, I am making this comment because it's 2015 and Array.isArray is supported by most browsers now, so to me that is now the correct answer to the question "Check if object is array?" that people should be referred to. – Patrick Finnigan
upvote
  flag
10 upvote
  flag
Live in the modern world - Array.isArray(obj) – mcfedr
upvote
  flag
Why is call significant? Why does Object.prototype.toString([]) return [object Object] and not [object Array]? – John Leidegren
upvote
  flag
@JohnLeidegren: Because this version of the .toString() method is reporting the [[Class]] property of its this value. The .call() method lets you manually set the value of this in the method being called to the first argument you provide. So with Object.prototype.toString([]), the value of this is the Object.prototype object. But if you use .call(), the value of this is your [] array. – user1106925
upvote
  flag
Worth noting that Array.isArray is not supported by IE 8 and below. Also as the function will not return true for array-like objects such as a NodeList (which are returned via querySelectorAll and similar functions). – Brian
upvote
  flag
in today angular world: angular.isArray(obj); – Tohid
upvote
  flag
in this benchmark typeof is fastest jsben.ch/#/tKVuy – Tschallacka
1 upvote
  flag
@MartinKonicek—jQuery's isArray is identical to the answer where Array.isArray is absent. Why should it be mentioned? – RobG
upvote
  flag
@T.J.Crowder: Could you elaborate why on your blog you say constructor is not the way to go. Several people on here are noting its the best supported and fastest option? Would really help understand your thoughts. – redfox05
1 upvote
  flag
@redfox05: Two reasons: 1. In ES5 code, people tend to forget to set it. 2. It doesn't play well with inheritance. Suppose you have Animal, and from Animal you derive Cat. If you use a constructor check, a cat won't be an animal, which is silly: They are, they're just a specific kind of animal. – T.J. Crowder
upvote
  flag
@T.J.Crowder Thanks for the reply! We're creating a util function/class to do the toString method (above) for everything that is not gonna return [object Object] and then use constructor.name for Objects and custom objects. Thoughts? P.s. you also mentioned certain anti-patterns? – redfox05
upvote
  flag
@redfox05: The function name property is fairly new and only recently supported, so you might have an issue there... – T.J. Crowder
upvote
  flag
Note that in another benchmark performed at jsben.ch, the typeof method is even slightly faster, but has some weird quirks, as mentioned in the beginning of T.J. Crowder's blog – Douwe de Haan
upvote
  flag
@DouwedeHaan I think typeof [] will return 'object', I made another benchmark to test instanceof operator and it was the fatest – YouneL
up vote 1074 down vote accepted

I would first check if your implementation supports isArray:

if (Array.isArray)
    return Array.isArray(v);

You could also try using the instanceof operator

v instanceof Array
83 upvote
  flag
+1 for instanceof Array. Simplest AFAICT – Tom Auger
112 upvote
  flag
v instanceof Array will return false if v was created in another frame (v is instance of thatFrame.contentWindow.Array class). – pepkin88
30 upvote
  flag
@JinuJD - I'm not sure what you're doing but I tested this in Firefox and IE and it still works. – ChaosPandion
39 upvote
  flag
To be specific: Array.isArray is defined as part of ECMAScript 5/Javascript 1.8.5. – jevon
7 upvote
  flag
Really simple and neat solution BUT isArray is not compatible with some older browsers (e.x. IE7 and IE8). Source: kangax.github.io/es5-compat-table/# – Wookie88
upvote
  flag
@JinuJosephDaniel - might be you're using uppercase O in instanceOf there. – Hammad Akhwand
upvote
  flag
I would never use isArrary, way too slow. You can use variable.constructor === Array. Way faster since all arrays are just objects in javascript. //allinonescript.com/questions/767486/… has more explanation and a jsperf link – jemiloii
1 upvote
  flag
How about: if (Array.isArray) return Array.isArray(v); else return v instanceof Array; – lewdev
1 upvote
  flag
or just: return (Array.isArray && Array.isArray(v)) || (v instanceof Array); – Stijn de Witt
1 upvote
  flag
This is what AngularJS does now through its angular.isArray(v) – Javarome
upvote
  flag
Well, IE9 is tricky, all else is fine. See here for elegant polyfill ➪ developer.mozilla.org/de/docs/Web/JavaScript/Reference/… – Frank Nocke
1 upvote
  flag
This should be the accepted answer here, imho. instanceOf never fails, not really sure about browser support, but at the time of writing (2k17) I don't think this is much of a problem anymore. – Automagisch
upvote
  flag
@Automagisch Agreed. Support is good enough now :-) – mpen

You can try this approach: http://web.archive.org/web/20100424091244/http://www.ajaxdr.com/code/javascript-version-of-phps-is_array-function/

EDIT: also, if you are already using JQuery in your project, you can use its function $.isArray().

2 upvote
  flag
Nice find with the jQuery route - few of us really explore the wealth of its less frequently used functions! – Dav
upvote
  flag
+1 Good find! Didn't know there was a jQuery isArray, this would have been useful quite some time ago – William Isted
2 upvote
  flag
In your approach all objects which contains property push will be array: is_array({push: true});//true – CruorVult

If the only two kinds of values that could be passed to this function are a string or an array of strings, keep it simple and use a typeof check for the string possibility:

function someFunc(arg) {
    var arr = (typeof arg == "string") ? [arg] : arg;
}
upvote
  flag
Yeah... that'd work for this scenario, but not in general. Ended up using varargs anyway. :) – mpen

The best solution I've seen is a cross-browser replacement for typeof. Check Angus Croll's solution here.

The TL;DR version is below, but the article is a great discussion of the issue so you should read it if you have time.

Object.toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)

// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};

jQuery also offers an $.isArray() method:

var a = ["A", "AA", "AAA"];

if($.isArray(a)) {
  alert("a is an array!");
} else {
  alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

16 upvote
  flag
27 upvote
  flag
Just a note, jQuery uses the toString method internally: GitHub Source – Jacob Squires
5 upvote
  flag
@JacobSquires it depends. I just tested here, latest jQuery on Chrome - $.isArray === Array.isArray is returning true. – Renan
2 upvote
  flag
@Renan: This is the good thing about using jQuery. It usually uses the most modern and best method to do it, and you don't have to do all the feature checking yourself to know what to use. – awe
upvote
  flag
jQuery is using Array.isArray behind the scenes: github.com/jquery/jquery/blob/master/src/core.js#L211 – Sergiu
1 upvote
  flag
But no one is going to use jQuery JUST FOR this functionality, right? I wouldn't just download jquery because I want to check if something is an array :p – Automagisch

I know, that people are looking for some kind of raw javascript approach. But if you want think less about, take a look here: http://underscorejs.org/#isArray

_.isArray(object) 

Returns true if object is an Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
6 upvote
  flag
"Unless another tag for a framework/library is also included, a pure JavaScript answer is expected." – Michał Perłakowski

I would make a function to test the type of object you are dealing with...

function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }

// tests
console.log(
  whatAmI(["aiming","@"]),
  whatAmI({living:4,breathing:4}),
  whatAmI(function(ing){ return ing+" to the global window" }),
  whatAmI("going to do with you?")
);

// output: Array Object Function String

then you can write a simple if statement...

if(whatAmI(myVar) === "Array"){
    // do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
    // do string stuff
}
upvote
  flag
nice! could be good for repeating check! – Alireza

Simple function to check this:

function isArray(object)
{
    if (object.constructor === Array) return true;
    else return false;
}
14 upvote
  flag
I'd reduce that down to one line return object.constructor === Array -- but are you sure that this will only return true for arrays? – mpen
10 upvote
  flag
Can do that with all boolean expressions. Drives me nuts when I see if(x) return true; else return false :-) Even if it's backwards, you should negate the expression. – mpen
upvote
  flag
Oh, it does indeed only return true for arrays, as far as I have found. var array_1 = new Array();//isArray(array_1) returns true var array_2 = [];//isArray(array_2) returns true It does not return true for array-like objects, such as those returned by getElementsByTagName, however. – MidnightTortoise
upvote
  flag
It's not really a big deal, won't make a difference in performance. Just a matter of style/preference I guess. I find it easier to read. – mpen
upvote
  flag
Due to the fact that your solution won't work with arrays from commands like getElementByName, I provided another solution. Any test results or commentaries are welcomed! – Marcus
3 upvote
  flag
The reason this doesn't return true for getElementsByTagName, is because the result of that function is actually an HTMLCollection and not an array. – Yuval A.
upvote
  flag
Just use this object.constructor === Array, you don't need a function for built in javascript properties. Arrays are objects and have access to the constructor property. – jemiloii
4 upvote
  flag
This fails badly if object is undefined or null. – John Henckel
1 upvote
  flag
@JohnHenckel See my answer //allinonescript.com/a/29400289/34806 it takes into account both your concern as well as the very first comment, all on one line – George Jempty

As MDN says in here:

use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays

Like this:

  • Object.prototype.toString.call(arr) === '[object Array]', or

  • Array.isArray(arr)

Array.isArray works fast, but it isn't supported by all versions of browsers. So you could make an exception for others and use universal method:

    Utils = {};    
    Utils.isArray = ('isArray' in Array) ? 
        Array.isArray : 
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }
1 upvote
  flag
You might like to add an explanation of the code to make it easier to understand for other users, but otherwise - nice. +1 – Jeff
3 upvote
  flag
You need to get the .toString() method from Object.prototype. Right now you're using the window.toString(), which isn't the same. – the system
upvote
  flag
You are right. window.toString do the same as Object.prototype.toString just in Chrome. – CruorVult
5 upvote
  flag
wow ('isArray' in Array). Never saw it before. thks – Ivan Ferrer Villa
upvote
  flag
isArray is not fast at all. It is the slowest method. – jemiloii
upvote
  flag
Why not just add it to Array rather than Utils? (I know you don't want extra properties on new array objects but I think that only happens if you add isArray to Array.prototype.) – David Winiecki

Here's my lazy approach:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

I know it's sacrilege to "mess with" the prototype, but it appears to perform significantly better than the recommended toString method.

Note: A pitfall of this approach is that it wont work across iframe boundaries, but for my use case this is not an issue.

upvote
  flag
Does work on IE8 32bit and 64bit. – datico
upvote
  flag
its not better in terms of performance anymore, at least on FF30 on Ubuntu 64-bit – test30
2 upvote
  flag
fooled by wat = {array_: true} objects. – Bergi
upvote
  flag
@Bergi: Yes, that should be obvious. If you're setting obj.array_ = true, then you're only fooling yourself. – namuol
upvote
  flag
@namuol: I'm not necessarily fooling myself. Often enough objects are used as dictionaries. Think of a cache object to memoize search results which uses the search strings as property keys. What if a user searches for array_? Does your object become an array because of that? It's just a bug. – Bergi
upvote
  flag
@namuol: Also, this approach would require that all involved parties (including used libraries) can agree that .array_ is used for tagging arrays. That's really not the case here, .array can mean anything. You should at least use a descriptive string, and signal inappropriateness of arbitrary use, e.g. with .__isArray = true. – Bergi
upvote
  flag
Agreed! Naming is important. This answer was just a quick hack meant to be used "in a vacuum" -- not really meant for use in libraries. – namuol
upvote
  flag
Potentially fooled by JSON.parse(someDataFromElsewhere).items.array_ returning true. – Roy Tinker

You can check the type of your variable whether it is an array with;

var myArray=[];

if(myArray instanceof Array)
{
....
}
1 upvote
  flag
A few people have already mentioned instanceof.. I think it fails under a few weird scenarios. – mpen

Since I don't like any Object.prototype-calls, I searched for another solution. Especially because the solutions of ChaosPandion won't always work, and the solution of MidnightTortoise with isArray() doesn't work with arrays coming from the DOM (like getElementsByTagName). And finally I found an easy and cross-browser solution, which probably also would have worked with Netscape 4. ;)

It's just these 4 lines (checking any object h):

function isArray(h){
    if((h.length!=undefined&&h[0]!=undefined)||(h.length===0&&h[0]===undefined)){
        return true;
    }
    else{ return false; }
}

I already tested these arrays (all return true):

1) array=d.getElementsByName('some_element'); //'some_element' can be a real or unreal element
2) array=[];
3) array=[10];
4) array=new Array();
5) array=new Array();
   array.push("whatever");

Can anybody confirm that this works for all cases? Or does anybody find a case where my solution don't work?

upvote
  flag
Absolutely. As a trivial example: jsfiddle.net/mnbayazit/fDwwV – mpen
2 upvote
  flag
Too many false positives. isArray(function(){}); // true, isArray("foo"); // true, isArray({length:0}); // true – the system
2 upvote
  flag
...and a NodeList isn't an Array anyway. – the system
upvote
  flag
Thanks for sharing your test results. This is getting my a lot more insight how Javascript works internally. – Marcus
upvote
  flag
The usage of charAt just vanished everywhere out of my code. ;) – Marcus
upvote
  flag
It turned out that in JS all strings are functions: alert("foo".constructor);, and arrays are functions: var bar=["id","12345"]; alert(bar.constructor);, or even structures like this: foobar={"id":"12345"}; which can be proved by alert(foobar.constructor);. But the problem is: Some functions are even arrays, e.g. strings are array. ;) – Marcus
upvote
  flag
The prove: "foo"[0] //returns "f"!, so strings are arrays and "foo".charAt(0) is not really needed in Javascript. – Marcus

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray

Array.isArray = Array.isArray || function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
};
A = [1,2,3]
console.log(A.map==[].map)

In search for shortest version here is what I got so far.

Note, there is no perfect function that will always detect all possible combinations. It is better to know all abilities and limitations of your tools than expect a magic tool.

upvote
  flag
slight derivation of mine A.map !== undefined but yeah, that could be slippy road in the world of monkey patchers ;) – dmi3y
upvote
  flag
FYI: This doesn't work across iFrames (//allinonescript.com/questions/460256/…) – WiredPrairie
function isArray(value) {
    if (value) {
        if (typeof value === 'object') {
            return (Object.prototype.toString.call(value) == '[object Array]')
        }
    }
    return false;
}

var ar = ["ff","tt"]
alert(isArray(ar))

There is a nice example in Stoyan Stefanov's book JavaScript Patterns which suppose to handle all possible problems as well as utilize ECMAScript 5 method Array.isArray().

So here it is:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}

By the way, if you are using jQuery, you can use it's method $.isArray()

2 upvote
  flag
+1: why not just a simple if(!Array.isArray) {... ? – Marco Demaio

In modern browsers you can do

Array.isArray(obj)

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

For backward compatibility you can 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
15 upvote
  flag
Array.isArray(obj) also works in nodejs. – neoneye
4 upvote
  flag
Here is a more complete list of browsers that support Array.isArray – lightswitch05

A simple function for testing if an input value is an array is the following:

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

This works cross browser, and with older browsers. This is pulled from T.J. Crowders' blog post

This is my attempt to improve on this answer taking into account the comments:

var isArray = myArray && myArray.constructor === Array;

It gets rid of the if/else, and accounts for the possibility of the array being null or undefined

upvote
  flag
constructor is not available in ES5 – TechTurtle
upvote
  flag
@TechTurtle Are you sure? This code runs in ES6 – George Jempty

I do this in a very simple way. Works for me. Any drawbacks?

Array.prototype.isArray = true;

a=[]; b={};
a.isArray  // true
b.isArray  // (undefined -> false)
6 upvote
  flag
fooled by {isArray:true} – Bergi
upvote
  flag
JSON.parse(someDataFromElsewhere).items.isArray could return true (depending on the data) and break your code. – Roy Tinker

I know this is an old question but here is a solution that I came up with and have been using for my projects...

function isArray (o) {
    return typeof o === "object" && o.length !== undefined;
}

isArray({}); // false
isArray(1); // false
isArray("str"); // false
isArray(function(){}); // false

isArray([]); // true

The only pitfall is that it will give a false positive if your object happens to have a length property:

isArray({length:0}); // true

If you are okay with that drawback and know your pure objects won't have that property, it's a clean solution and should be faster than the Object.prototype.toString.call method.

upvote
  flag
isArray( new String() ); returns true – László Kardinál
upvote
  flag
Yes, I noted that as a pitfall in my comments below the examples: "The only pitfall is that it will give a false positive if your object happens to have a length property" – Sensei_Shoh
var is_array = function (value) {
   return value &&
     typeof value === 'object' &&
     typeof value.length === 'number' &&
     typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

This function has been taken from "JS the good parts" book, works perfect for me.

upvote
  flag
var object = {splice: function(){}}; Object.defineProperty(object, "length", {value: 1, enumerable: false}); console.log(is_array(object)); – Michał Perłakowski
 var length = 16;                               // Number
 var lastName = "Johnson";                      // String
 var cars = ["Saab", "Volvo", "BMW"];           // Array
 var x = {firstName:"John", lastName:"Doe"};

 Object.prototype.myCheck= function(){
 if (this.constructor === Array){
          alert('array');
        }else if (this.constructor === Object)
       {
         alert('object');
        }else if (this.constructor === Number)
        {
          alert('number');
        }else if (this.constructor === String)
        {
          alert('string');
        }

 }
 cars.myCheck();
 lastName.myCheck();
 length.myCheck();
1 upvote
  flag
Why did you make your method a prototype of Object if you aren't going to call it like cars.myCheck()? – mpen
upvote
  flag
yes mark you are correct it should be cars.myCheck().. updated the answer – Gaurav
2 upvote
  flag
Still no. If you're making it a prototype method, you should drop the obj argument and use this inside instead. Also, a function that just alerts isn't of much use to anyone. – mpen

I have updated the jsperf fiddle with two alternative methods as well as error checking.

It turns out that the method defining a constant value in the 'Object' and 'Array' prototypes is faster than any of the other methods. It is a somewhat surprising result.

/* Initialisation */
Object.prototype.isArray = function() {
  return false;
};
Array.prototype.isArray = function() {
  return true;
};
Object.prototype._isArray = false;
Array.prototype._isArray = true;

var arr = ["1", "2"];
var noarr = "1";

/* Method 1 (function) */
if (arr.isArray()) document.write("arr is an array according to function<br/>");
if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");
/* Method 2 (value) - **** FASTEST ***** */
if (arr._isArray) document.write("arr is an array according to member value<br/>");
if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");

These two methods do not work if the variable takes the undefined value, but they do work if you are certain that they have a value. With regards to checking with performance in mind if a value is an array or a single value, the second method looks like a valid fast method. It is slightly faster than 'instanceof' on Chrome, twice as fast as the second best method in Internet Explorer, Opera and Safari (on my machine).

This is the fastest among all methods (all browsers supported):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}
2 upvote
  flag
You're right, that is the fastest according to the tests I included in the question. – mpen
3 upvote
  flag
Are there any downsides to using this method? It seems much more simple and effective than the accepted, top answer. – David Meza
upvote
  flag
@shinobi - just curious (and i've seen this often) - why do you phrase the condition if (obj && Array === obj.constructor) as opposed to if (obj && obj.constructor === Array) ? Is it a lost in translation to english, then to code thing? eg, english speakers generally tend to ask "does the object exist, and does it's constructor come from the array class?", so the code flow when reading it is more logical. or is there some technical reason? – unsynchronized
upvote
  flag
function object_type(o){var t = typeof(o);return ((t==="object") && (o.constructor===Array)) ? "array" : t;} /*allows you to */ switch(object_type(o)){ case 'array': break; case 'object' : o.dosomething();} – unsynchronized
upvote
  flag
@unsynchronized I dont really know of any technical reason. Even I have seen this often, so got used to it. – shinobi
3 upvote
  flag
@shinobi all good. i suppose it might be a hangover from a safe c habit - if you accidentally use = instead ==, it would not compile as its not an assignable variable. – unsynchronized
upvote
  flag
@unsynchronized: Ah. I see. That could be it. I have actually posted this as a question. //allinonescript.com/questions/38035875/… – shinobi
upvote
  flag
doesn't work on isArray(jQuery('div')) .. but is obviously an array... not sure what kind of special array jquery uses but it should be ok – momomo
upvote
  flag
@momomo jQuery doesnt return an Array. Its returns an array-like object. See this //allinonescript.com/questions/1302428/… – shinobi

You can try this:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false
upvote
  flag
there are many easier ways to do this! – Alireza

You can use this function to get data type.

var myAr  = [1,2];

checkType(myAr);

function checkType(data){
  if(typeof data ==='object'){
    if(Object.prototype.toString.call(data).indexOf('Array')!==(-1)){
      return 'array';
    } else{
      return 'object';
    }
  } else {
    return typeof data;
  }
}

if(checkType(myAr) === 'array'){console.log('yes, It is an array')};
upvote
  flag
All the op asked for was a simple efficient check. – Kermit_ice_tea

The following could be used if you know that your object doesn't have a concat method.

var arr = [];
if (typeof arr.concat === 'function') {
    console.log("It's an array");
}

upvote
  flag
This is a good trick, but could be overridden... but most of the times should get the result – Alireza

This function will turn almost anything into an array:

function arr(x) {
    if(x === null || x === undefined) {
        return [];
    }
    if(Array.isArray(x)) {
        return x;
    }
    if(isString(x) || isNumber(x)) {
        return [x];
    }
    if(x[Symbol.iterator] !== undefined || x.length !== undefined) {
        return Array.from(x);
    }
    return [x];
}

function isString(x) {
    return Object.prototype.toString.call(x) === "[object String]"
}

function isNumber(x) {
    return Object.prototype.toString.call(x) === "[object Number]"
}

It uses some newer browser features so you may want to polyfill this for maximum support.

Examples:

> arr(null);
[]
> arr(undefined)
[]
> arr(3.14)
[ 3.14 ]
> arr(1/0)
[ Infinity ]
> gen = function*() { yield 1; yield 2; yield 3; }
[Function: gen]
> arr(gen())
[ 1, 2, 3 ]
> arr([4,5,6])
[ 4, 5, 6 ]
> arr("foo")
[ 'foo' ]

N.B. strings will be converted into an array with a single element instead of an array of chars. Delete the isString check if you would prefer it the other way around.

I've used Array.isArray here because it's the most robust and also simplest.

imagine you have this array below:

var arr = [1,2,3,4,5];

Javascript (new and older browsers):

function isArray(arr) {
  return arr.constructor.toString().indexOf("Array") > -1;
}

or

function isArray(arr) {
  return arr instanceof Array;
}

or

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

then call it like this:

isArray(arr);

Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

jQuery:

$.isArray(arr);

Angular:

angular.isArray(arr);

Underscore and Lodash:

_.isArray(arr);

easiest and fastest way to check if an Object is an Array or not.

 var arr = [];
  arr.constructor.name ==='Array'  //return true;

or

arr.constructor ===Array //return true;

or you can make a utility function:

function isArray(obj){ return obj && obj.constructor ===Array}

usage:

isArray(arr); //return true

You can find with push like below:

function isArray(obj){
   return (typeof obj.push=== 'function')?true:false;
}

var array=new Array();
or
var array=['a','b','c'];
console.log(isArray(array));

There's just one line solution for this question

x instanceof Array

where x is the variable it will return true if x is an array and false if it is not.

upvote
  flag
Much cleaner and future safe! This or a typeof comparison. – ChristoKiwi
upvote
  flag
Is this something that receives a good amount of browser support? I like it. – Daniel Zuzevich

In your case you may use concat method of Array which can accept single objects as well as array (and even combined):

function myFunc(stringOrArray)
{
  var arr = [].concat(stringOrArray);

  console.log(arr);

  arr.forEach(function(item, i)
  {
    console.log(i, "=", item);
  })
}

myFunc("one string");

myFunc(["one string", "second", "third"]);

concat seems to be one of the oldest methods of Array (even IE 5.5 knows it well).

Not the answer you're looking for? Browse other questions tagged or ask your own question.