Question

I grew a little frustrated with the built-in typeof method, as it doesn't handle it's job very well. Is adding a type property to the object prototypes a bad idea, and (if so) why is that?

Array.prototype.type = "Array";
Object.prototype.type = "Object";
Function.prototype.type = "Function";
String.prototype.type = "String";
Number.prototype.type = "Number";


function typeOf(obj) {
    if (!obj) return obj; // Returns undefined and null values.

    return obj.type;
}
Was it helpful?

Solution

You can do something like this

function typeOf(inputArg) {
    if (!arguments.length) {
        throw new SyntaxError();
    }

    if (typeof inputArg === 'undefined') {
        return 'undefined';
    }

    if (inputArg === null) {
        return 'null';
    }

    return ({}.toString.call(inputArg).match(/\[object (Number|Boolean|String|Array|Object|Function)\]/) || ['Object']).pop().toLowerCase();
}

console.log(typeOf(undefined));
console.log(typeOf(null));
console.log(typeOf(1));
console.log(typeOf(true));
console.log(typeOf(''));
console.log(typeOf([]));
console.log(typeOf({}));
console.log(typeOf(function () {}));
console.log(typeOf(/a/));
console.log(typeOf());

Output

undefined
null
number
boolean
string
array
object
function
object
Uncaught SyntaxError 

On jsFiddle

However, there are some other bugs in older browsers which can still cause different results. And this does not take into account E4X XML stuff, or any new types that may get defined in ECMA next (though probably nothing new). You also need to be aware that this will identify primitive objects, i.e. new String('hello') as a string rather than an object, which may not be what you desire. So you need to think carefully as to your needs or what you are trying to achieve (which I'm not totally clear about).

OTHER TIPS

If you're just looking for a way to test for types 'lodash' (and probably 'underscore') brings functions that might test in a way more to your liking:

http://lodash.com/docs#isArray (and all other _.is* functions)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top