Skip to content

Instantly share code, notes, and snippets.

@petrosalema
Created June 21, 2011 21:59
Show Gist options
  • Save petrosalema/1039024 to your computer and use it in GitHub Desktop.
Save petrosalema/1039024 to your computer and use it in GitHub Desktop.
typecheck: Better alternative to JavaScript's typeof operator
// Uber typeof:
// Since null, in JavaScript, is an object with an unknown value,
// typeof null == 'object' is technically correct.
// Nevertheless, JavaScript's typeof operator could be much more helpful
// than it is.
function typecheck (obj) {
var type;
// faster than if/else
switch (obj) {
case undefined:
type = 'undefined';
break;
case null:
type = 'null';
break;
default:
var m = (obj.constructor + '').match(/function\s+([a-z_$][0-9a-z_$]*)/i);
if (m == null) {
type = typeof obj;
} else if (m.length > 0) {
type = m[1].toLowerCase();
} else {
type = typeof obj;
}
}
return type;
};
@elijah629
Copy link

elijah629 commented Jul 19, 2022

var toType = function (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

@petrosalema
Copy link
Author

petrosalema commented Jul 19, 2022

var toType = function (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

Nice @elijah629 👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment