jquery get variable type

Sam Deering
Share

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