Created
June 21, 2011 21:59
-
-
Save petrosalema/1039024 to your computer and use it in GitHub Desktop.
typecheck: Better alternative to JavaScript's typeof operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
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