Home > JavaScript > Identifying an array in JavaScript

Identifying an array in JavaScript

In JavaScript using typeof operator we can find the type of the variable used in the script. But it sometimes produce some confusing values for the developer especially for the novice ones. Consider the following code

var foo = {
	'name': 'Jayaprakash',
	'job': 'Web Team Lead'
};

If you want to determine the type of the object literal foo it is quite simple

console.log(typeof foo); //Outputting it to the browser console

The output would be ‘object‘. Pretty simple, right?

Now consider an example with an Array

var foo = [];
foo.push(1);
foo.push(2);

You want to determine the type of the array vaiable foo

console.log(typeof foo);

The output would be ‘object‘. Bit confusing you may be expecting array as the output. This is because JavaScript treats arrays as object (most of the items in JavaScript are considered as objects) in it. As a result when you determine the type of it, it will give you a value of object.

The question at this point is, is there any way through one can determine whether a variable is array or not? Yes we have a simple method for doing that

var isArray = function(arr){
	return Object.prototype.toString.call(arr).toLowerCase().indexOf('[object array]') !== -1;
}

This function will return true if the argument is a JavaScript array else it will return false.

Advertisements
Categories: JavaScript
  1. October 20, 2012 at 4:13 am

    Hurrah! After all I got a weblog from where I be able to in fact obtain valuable facts concerning my study and knowledge.

    Pablo

  2. deepu
    March 4, 2013 at 6:57 am

    This is very useful! Thanks!!

  3. January 31, 2015 at 2:01 pm

    Tested
    Thank You 🙂

  1. No trackbacks yet.

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

%d bloggers like this: