jQuery: $.type()

This post covers all about jQuery’s .type() method. You will learn what it does, see its’ usage examples and understand the difference between jQuery’s .type() and JavaScripts’ typeof operator.

Without further ado, let’s find an answer to the following question.

What does $.type() do?

jQuery.type() method returns internal JavaScript class name of the passed argument.

jQuery.type(1)       // "number"
jQuery.type("foo")   // "string"
$.type(true)         // "boolean"
$.type(undefined)    // "undefined"
$.type(function(){}) // "function"
$.type(new Date())   // "date"
$.type(/test/)       // "regexp"
$.type(null)         // "null"

You might argue, why should I use jQuery .type() function when JavaScript already has native typeof operator that does just that. Well, you are in luck. In our previous post I explained why JavaScript’s typeof operator fails in what it’s supposed to do and excels in something else. Take the time and read the article.

When would you need it?

The method is very handy when writing a jQuery plugin or a function that can receive different type of arguments (e.g. $.css(Array or String)) or take optional parameters (e.g. $.click([eventData], function)).

In the case of $.click() method above:

/* You can either check:
  - eventData's type
  - fn === undefined
*/
click: function(eventData, fn){

    if($.type(fn) === "undefined"){
      fn = eventData;
      eventData = {default: "value"};
    }

}

Notes and Caveats

I would like to leave you with some notes on $.type() method:

  • as of jQuery 1.9 $.type(new Error()) will return "error"
  • if the argument type is not one of the list below, method will return "object":
    • Boolean
    • Number
    • String
    • Function
    • Array
    • Date
    • RegExp
    • Object
    • Error