Skip to content

Instantly share code, notes, and snippets.

@n1k0
Created November 2, 2011 08:57
Show Gist options
  • Save n1k0/1333210 to your computer and use it in GitHub Desktop.
Save n1k0/1333210 to your computer and use it in GitHub Desktop.
A better typeof for JavaScript, with tests cases
/**
* @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));
});
-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'
@artsyca
Copy link

artsyca commented Feb 27, 2013

Not sure if this works for uninstantiated variables..

betterTypeOf(xxx) // ReferenceError: xxx is not defined

Edit: This is mentioned in the original article as a limitation of using a function in place of the native typeof.

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