How To Check If something is an Array in Javascript

Standard
In order to check whether some item is an object or an array, Javascript does not provide a direct way to do so. So, here is a solution that is a work-around.
var is_array = function(value){
  return value &&
         typeof value === 'object' &&
         typeof value.splice === 'function' &&
         typeof value.length === 'number' &&
         !(value.propertyIsEnumerable('length'));
};

That is all you need to cheek if anything is an array or something else. Enjoy!!

After posting this code snippet, someone through the comments mentioned the introduction of Array.isArray() and here is how it works:

var myarray = [3,53,1,[3,2],100];

console.log(Array.isArray(myarray);
//this one returns true.

Good day!

Advertisements

21 thoughts on “How To Check If something is an Array in Javascript

    • Impressive there. Thanks for the link. I will be looking behind the scenes of that isArray() method.

      One thing about Javascript Arrays is that during the language design, they were not really arrays but objects with array characteristics. It is good now that they have added the method.

  1. isArray won’t work ie8 and below, but compatibility code available at MDN. I think we can use following code also.

    var is_array = function(value){
    return value.splice ? true : false || false;
    }

    Eg: is_array([]) //true
    is_array({}) //false

    • Thank you so much for your comment there. I can see why checking to see whether value has a splice method in it because only an array would do.
      Thanks again!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s