Skip to content

Instantly share code, notes, and snippets.

@matheuseduardo
Last active June 17, 2016 19:23
Show Gist options
  • Save matheuseduardo/9f3a80685e20885f57d0ca0b6f3c11cf to your computer and use it in GitHub Desktop.
Save matheuseduardo/9f3a80685e20885f57d0ca0b6f3c11cf to your computer and use it in GitHub Desktop.
get type of objects, errors, etc. in javascript
var type = (function (global) {
var cache = {};
return function (obj) {
var key;
return obj === null ? 'null' // null
: obj === global ? 'global' // window in browser or global in nodejs
: (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
: obj.nodeType ? 'object' // DOM element
: cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
|| (cache[key] = key.slice(8, -1)); // get XXXX from [object XXXX], and cache it
};
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment