How To Detect Varible Type In JavaScript

In Javascript, finding type is bit tricky because everything is an object in javascript. For example, if you take a number 5 and if check it with typeof keyword as typeof new String("foo") it will give u object. Though, it works fine with literals(number,bool, sting... only). Again it won't work with Array literals.

I mean if you use
var a=[]; typeof a //should give you object. In order to solve all these issues I have created this small script to check the types.

var typeCheck = {  
    isArray: function(what) {
        return Object.prototype.toString.call(what) === '[object Array]';
    },
    isObject: function(what) {
        return ((typeof what == "object") && (what !== null));
    },
    isNumber: function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    },
    isDate: function(d) {
        if (Object.prototype.toString.call(d) !== "[object Date]")
            return false;
        return !isNaN(d.getTime());
    },
    isFunction: function(obj) {
        return !!(obj && obj.constructor && obj.call && obj.apply);
    }
};

Now, If you want to check if an array is really an array or not you can write code as.

var a=[];  
typeCheck.isArray(a); 

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.