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