JavaScript
Article

jquery get variable type

By Sam Deering

To get the a variables type using jQuery there is a jQuery function called .type() which returns “array”, “string”, “number”, “function”, “object” etc… At first thoughts I thought it must be very similar to the typeOf() JavaScript function. But as you can see in it’s implementation it’s using tostring() and class2type() checks. Interesting.

type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ toString.call(obj) ] || "object";
	},

A closer look at the class2type object implementation.

var class2type = {
    "[object Array]": "array",
    "[object Boolean]": "boolean",
    "[object Date]": "date",
    "[object Function]": "function",
    "[object Number]": "number",
    "[object Object]": "object",
    "[object RegExp]": "regexp",
    "[object String]": "string"
};

Example use of jQuery.type() function.

var $forms = Array($('#register-form1'), $('#register-form2'), $('#register-form3'));
console.log($.type($forms));
//output: array
  • Soren

    A much better way:

    var obj = new Array();
    var objectType = Object.prototype.toString.call(obj);

    “objectType” contains “[object Array]”.

    If you apply this function you can get just “Array”:

    var toType = function(obj)
    {
    return ({}).toString.call(obj).match(/s([a-z|A-Z]+)/)[1].toLowerCase()
    }

    • jquery4u

      @Soren, thx for sharing

  • srawan verma

    fleg is very smoll dont see your fleg

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.