Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JS: A Better typeof operator
/**
* A better, more reliable way to handle `typeof` checking.
*
* @source http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
*
*/
Object.toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// Alternatively you might choose to add the toType function to a namespace of your own, such as util.
// We could get a little cleverer (inspired by Chrome’s use of “global” for window.[[Class]]).
// By wrapping the function in a global module we can identify the global object too:
Object.toType = (function toType(global) {
return function(obj) {
if (obj === global) {
return "global";
}
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
})(this)
// Usage
Object.toType([1,2,3]); //"array"
Object.toType(/a-z/); //"regexp"
Object.toType(JSON); //"json"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.