Check if a variable is an array in Javascript

Here’s a quick tip. When writing javascript and trying to test if a given variable is an array or not, I originally used the method of using the “typeof” operator. Unfortunately, because an array in Javascript is just another type of object, typeof will return “object” for an array variable.

So… instead, it’s recommended (by the people of the internet) that you use the “toString” method which will return a specific string for Array objects.  The following code demonstrates this:

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

// Create some test variables
var my_array = [ 'test1', 'test2' ];
var my_object = { 'test1' : 1, 'test2' : 2};
var my_string = 'blah';

// Try it out...
alert('my_array: ' + is_array(my_array));
alert('my_array: ' + is_array(my_object));
alert('my_string: ' + is_array(my_string));

So, if you try this code out, you should see three alert boxes with the following results:

my_array: true
my_object: false
my_string: false

That’s it.  If you have any comments/suggestions, please leave them below.

Leave a Comment