Check If an variable is an array or not in javascript

This js function will check if a variable / Object is an array or not and returns true or false

//chk if an object is an array or not.
function isArray(obj) {
//returns true is it is an array
if (obj.constructor.toString().indexOf(“Array”) == -1)
return false;
else
return true;
}

45 Replies to “Check If an variable is an array or not in javascript”

  1. I would normally use:
    var test = [];
    if ( test instanceof Array ) …
    since im not a fan of handling strings since it’s linda slow : P

  2. John-John Tedro’s solution seems much more elegant to me.

    Imagine a custom user object with a constructor that is not named `Array’, but contains the word “Array” in the code (in a string, or when using the Array constructor itself). In that case, your code would return inaccurate results for instances of that object.

  3. Dionysis Zindros is correct. When u have a custom user object with a constructor that is not named `Array?, then this method would not be correct. Is there any other solution for it?

  4. Unfortunately, you cannot test for arrays using instanceof. The following check returns false:
    ((new Array) instanceof Array)

    The following, on the other hand, returns true, and explains why you can’t use instance of to detect arrays:
    ((new Array) instanceof Object)

  5. hi all,

    anyone can tel me how to iterate the values of an array and compare with those values with string value.If it matchs it has to return true. else false . Using java script.

  6. hi all,

    i am adding some values to javascript array.
    i want to compare each value with string constant(lets say “false”),
    if any one item of array match with the string constant i have return true,
    else false.Using java script.

    Help me in this regard.

    Raja.

  7. Regarding AJ’s post, who is wrong with his statement:

    ((new Array) instanceof Array)
    returns true to me in at least IE5.5+, Firefox 2.0+, Opera 9.1+

    Of course
    ((new Array) instanceof Object)
    returns true as well, as an Array is a “subtype” of Object

    But since we want to know if an Array is an Array, not if it’s an Object, we already have what we need. 😉

    Best, smilingrasta

  8. Well, we can check a bigger expression for a better precision.
    Like:
    obj.constructor.toString().indexOf(“function Array()”) != -1
    with this, we have a better acurancy of what we want.
    I will wait for observations.
    🙂
    []’s, Basalt

  9. Well, obj.constructor is undefined on IE6, so using this code doesn’t work either. It’s odd that it’s so hard to find whether something is array or not in Javascript. There’s got to be a solution.

  10. i just found my solution. Use this code:

    if(undefined != obj.length){
    // this means it’s Array, you can do whatever you like here.
    }

    You can test on different browsers.

  11. well, string also has length property so obj.length wont work either.

    Following could be close but not perfect yet. You can futher add obj.constructor mentioned above.

    typoeof(obj)== “object” && obj.length && typeof(obj.length)==”number”

  12. Hi, all

    Yes this is the best solution. Use this code:
    ‘undefined’ – use with single quot OR without single quot depend upon browswer.

    if(‘undefined’ != obj.length){
    // this means it?s Array, you can do whatever you like here.
    }

    You can test on different browsers.

  13. This object seems to work pretty well:

    var resolve = (function() {
    function what_is_it(o) {
    if (o === null) {
    return ‘null’;
    }
    return o.constructor.toString().split(‘ ‘)[1].replace(/\(\)/g,”).toLowerCase();
    }
    // Exposed methods
    return {
    ‘obj_is’ :function(o) { return what_is_it(o); }
    };
    })();

    // Test with:

    var ra = [];
    var st = ‘1,2,3,4’;
    var rb = st.split(‘,’);
    var no = {‘ra’:[1,2,3]};
    var bn = false;
    var nm = 4;
    var nu = null;
    var fn = function() { return false; };
    var a = [
    resolve.obj_is(ra),
    resolve.obj_is(st),
    resolve.obj_is(rb),
    resolve.obj_is(no),
    resolve.obj_is(bn),
    resolve.obj_is(nm),
    resolve.obj_is(nu),
    resolve.obj_is(fn),
    resolve.obj_is(no.ra)
    ];
    alert(a.join(‘\t\n’));

  14. if (obj.constructor === Array)
    won’t work because Array points to window.Array but the array you are testing may have been constructed in the context of a different window.

    🙁 sorry guys.

  15. ‘obj.constructor == Array’ will return false if the array has been been created literally, ie. ‘obj = [1,2,3]’.

  16. Just to elaborate a little more the the google crowd:
    it seems this works:
    (typeof obj == ‘object’ && typeof obj.length == ‘number’)

  17. What you really want to check is the object’s internal [[Class]] property:

    function classOf(o) {
    return {}.toString.call(o).slice(8, -1);
    }

    function isArray(o) {
    if ("Array" == classOf(o)) return true;
    return false;
    }

  18. Also, here’s a better classOf() function:

    function classOf(o) {
    if (undefined === o) return "Undefined";
    if (null === o) return "Null";
    return {}.toString.call(o).slice(8, -1);
    }

  19. @Mike Ter Louw,
    Nice one Mike, Will check with the solution you have provided.
    The ClassOf function is good.
    Let u know after give a try.

  20. How about using the prototype property of the object’s constructor to check for a property which is unique to Arrays?

    e.g.:

    if("push" in var.constructor.prototype) {
    // var is an Array.
    }

  21. Hey,

    I’m working with dates. Trying to make my own web calendar.
    Well, it’s almost done, I just find some problems when flagging day which has events.


    // "dias" is my array with busy days
    // "checkvar" is my variable with current day
    if ( (dias.join().indexOf(checkvar)>=0) )
    { document.getElementById('pre_1').className = 'normal_day' }
    else
    { document.getElementById('pre_1').className = 'event_day' }

    The problem is: in day 5/8/2011, for exemple, it flag how a event day, but it isn’t a event day, it’s because 15/8/2011 have events. And I can’t change my way to make the array, else some other things will not work as well.

    How can i change the way to look into the array in the Javascript for it don’t happen?

  22. How about this:

    Array.prototype.iAmAnArray = function(){
    return true;
    }

    Whenever you want to check do this:
    if(obj.iAmAnArray){
    // is an array
    }

  23. Ha, yeah. I’ve learnt better now. The prototype seems so convenient to mess with … until something breaks down the line! *sigh* oh well.

Leave a Reply to bcastill Cancel reply

Your email address will not be published. Required fields are marked *