Techumber
Home Blog Work

How To Detect Varible Type In JavaScript

Published on April 16, 2014

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);