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!