How To Detect Varible Type In JavaScript

Github avatar
April 16, 2014. 1 min read

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 Array]';
    isObject: function(what) {
        return ((typeof what == "object") && (what !== null));
    isNumber: function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    isDate: function(d) {
        if ( !== "[object Date]")
            return false;
        return !isNaN(d.getTime());
    isFunction: function(obj) {
        return !!(obj && obj.constructor && && obj.apply);

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

var a=[];