javascript print exact type of object

Solutions on MaxInterview for javascript print exact type of object by the best coders in the world

showing results for - "javascript print exact type of object"
Dylan
15 Oct 2016
1var type = (function(global) {
2    var cache = {};
3    return function(obj) {
4        var key;
5        return obj === null ? 'null' // null
6            : obj === global ? 'global' // window in browser or global in nodejs
7            : (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
8            : obj.nodeType ? 'object' // DOM element
9            : cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
10            || (cache[key] = key.slice(8, -1).toLowerCase()); // get XXXX from [object XXXX], and cache it
11    };
12}(this));
13
14//use as:
15
16type(function(){}); // -> "function"
17type([1, 2, 3]); // -> "array"
18type(new Date()); // -> "date"
19type({}); // -> "object"