Skip to content

Instantly share code, notes, and snippets.

@TJkrusinski
Created May 17, 2013 15:59
Show Gist options
  • Save TJkrusinski/5600070 to your computer and use it in GitHub Desktop.
Save TJkrusinski/5600070 to your computer and use it in GitHub Desktop.
Type checker for JS that actually works.
/**
* Taken from http://james.padolsey.com/javascript/checking-types-in-javascript/
*/
function type(o){
return !!o && Object.prototype.toString.call(o).match(/(\w+)\]/)[1];
}
type(101); // returns 'Number'
type('hello'); // returns 'String'
type({}); // returns 'Object'
type([]); // returns 'Array'
type(function(){}); // returns 'Function'
type(new Date()); // returns 'Date'
type(document); // returns 'HTMLDocument'
// For example, to test for an Array:
if( type([1,2,3,4,5]) === 'Array' ) doStuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment