Determine the type of an Object in JavaScript

In javascript, all the variables are declared as var. However, sometimes we need to know the type of var to implement your logic. This is how you can determine some of the data types.

//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 true;
    }
    else{
        return false;
    }
}

To get the datatype, do the following:

var boolVal = true;
var numVal = 123;
var strVal = "String";
alert(typeof boolVal)    // displays "boolean"
alert(typeof numVal)     // displays "number"
alert(typeof strVal)     // displays "string"

Advertisements

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