Skip to main content

Determine the internal JavaScript Class name of an object.

/**
 * Determine the internal JavaScript Class of an object.
 *
 * http://youmightnotneedjquery.com/#type
 * https://api.jquery.com/jQuery.type/
 *
 * @param {Anything} obj Object to get the internal JavaScript Class of.
 * @return {string}
 *
 * @example
 * getType(undefined === "undefined"
 * getType() === "undefined"
 * getType(window.notDefined === "undefined"
 * getType(null === "null"
 * getType(true === "boolean"
 * getType(new Boolean() === "boolean"
 * getType(3 === "number"
 * getType(function(){} === "function"
 * getType("test" === "string"
 * getType(new String("test") === "string"
 * getType(/test/ === "regexp"
 * getType(new Array() === "array"
 * getType(new Error() === "error"
 * getType(new Date() === "date"
 * getType(Symbol() === "symbol"
 * // Everything else returns "object" as its type.
 */
function getType(obj) {
    return Object.prototype.toString
        .call(obj)
        .replace(/^\[object (.+)\]$/, "$1")
        .toLowerCase();
}