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:
(function(){ var types = ['Array','Function','Object','String','Number'], typesLength = types.length; while (typesLength--) { window['is' + types[typesLength]] = (function(type){ return function(o) { return !!o && ( Object.prototype.toString.call(o) === '[object ' + type + ']' ); } })(types[typesLength]); } })(); // Usage: isFunction( function(){} ); // true isArray( [1,2,3,4,5] ); // true isNumber( 3334322 ); // true isObject( {a:1, b:2} ); // true isString( 'Hello!' ); // true |
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
what does “===” mean?
Hi Gman!
‘===’ is known as the strict equality operator. It is normally used instead of the well known general equality operator (‘==’). The only difference is that the former checks for type and the latter doesn’t. It’s best practice to use the strict version for that very reason.
An example:
just for reference, here are the official recommendations for doing these in jQuery: http://docs.jquery.com/JQuery_Core_Style_Guidelines
nice idea
Paul, those guidelines do prevent use of a switch() condition though, for better code-readability James’ method works nicely.
@James
ya, now I got it. Thank you
Why did you not simply use typeOf (http://docs.jquery.com/JQuery_Core_Style_Guidelines) ?
@GeekFG, did you read my post (or any of the other comments)? Typeof is okay for most cases but it reports certain types incorrectly. For example, this won’t work:
That’s why a added this link “http://docs.jquery.com/JQuery_Core_Style_Guidelines”.
When I want to check for an array I use jQuery.isArray(object).
Moreover Object.prototype is a better way for browsers compatibility than window[key] = function(){}