Checking types in JavaScript can be a little tricky, especially with browser (and language) quirks. In light of this recent article I’ve made a small helper function using the recommended method:
The Code:
function type(o){ return !!o && Object.prototype.toString.call(o).match(/(\w+)\]/)[1]; }
Usage:
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(); }
This new function makes a few improvements on the shameful typeof operator. For one thing you can now successfully test for an array!
Here’s an alternative implementation: