The most accurate way to check JS object's type?
The JavaScript specification gives exactly one proper way to determine the class of an object:
Object.prototype.toString.call(t);
http://bonsaiden.github.com/JavaScript-Garden/#types
the Object.prototype.toString
is a good way, but its performance is the worst.
http://jsperf.com/check-js-type
Use typeof
to solve some basic problem(String, Number, Boolean...) and use Object.prototype.toString
to solve something complex(like Array, Date, RegExp).
and this is my solution:
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).toLowerCase()); // get XXXX from [object XXXX], and cache it
};
}(this));
use as:
type(function(){}); // -> "function"
type([1, 2, 3]); // -> "array"
type(new Date()); // -> "date"
type({}); // -> "object"
Accepted answer is correct, but I like to define this little utility in most projects I build.
var types = {
'get': function(prop) {
return Object.prototype.toString.call(prop);
},
'null': '[object Null]',
'object': '[object Object]',
'array': '[object Array]',
'string': '[object String]',
'boolean': '[object Boolean]',
'number': '[object Number]',
'date': '[object Date]',
}
Used like this:
if(types.get(prop) == types.number) {
}
If you're using angular you can even have it cleanly injected:
angular.constant('types', types);