Created
November 2, 2011 08:57
-
-
Save n1k0/1333210 to your computer and use it in GitHub Desktop.
A better typeof for JavaScript, with tests cases
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
/** | |
* @see http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ | |
*/ | |
function betterTypeOf(input) { | |
try { | |
return Object.prototype.toString.call(input).match(/^\[object\s(.*)\]$/)[1].toLowerCase(); | |
} catch (e) { | |
return typeof input; | |
} | |
} | |
function Plop() { | |
this.foo = 2; | |
return { | |
do: function() { | |
return 42; | |
} | |
} | |
} | |
cases = [ | |
-1, | |
0, | |
2, | |
2.2, | |
[1, 2], | |
{a: 1}, | |
null, | |
undefined, | |
NaN, | |
Plop, | |
Plop(), | |
new Plop() | |
]; | |
cases.forEach(function(testCase) { | |
console.log(testCase, typeof testCase, betterTypeOf(testCase)); | |
}); |
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
-1 'number' 'number' | |
0 'number' 'number' | |
2 'number' 'number' | |
2.2 'number' 'number' | |
[ 1, 2 ] 'object' 'array' | |
{ a: 1 } 'object' 'object' | |
null 'object' 'null' | |
undefined 'undefined' 'undefined' | |
NaN 'number' 'number' | |
[Function: Plop] 'function' 'function' | |
{ do: [Function] } 'object' 'object' | |
{ do: [Function] } 'object' 'object' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure if this works for uninstantiated variables..
Edit: This is mentioned in the original article as a limitation of using a function in place of the native typeof.