Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
JS: A Better typeof operator
* A better, more reliable way to handle `typeof` checking.
* @source
Object.toType = function(obj) {
return ({})\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 ({})\s([a-z|A-Z]+)/)[1].toLowerCase();
// 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.