Why javascript's typeof always return "object"?

JS's typeof doesn't always return 'object', but it does return object for things which people may not consider to be objects -- ie arrays, and also, oddly, for nulls.

For arrays this is correct, because as far as JS is concerned, arrays are objects; they're the same thing. Array is just another class, and you can instantiate objects of type Array, but they're still treated as objects.

This page has a list of types in JS, along with the response you'll get for each of them from typeof. It also has some JS code to override the typeof function with one that returns more useful information. If you're worried about it not being useful, you could implement something like that if you wish.


It doesn't always return "object":

alert(typeof "hello");

That said, a (possibly) more useful trick to examine objects is to use Object.prototype.toString.call() and look at the result:

var t = Object.prototype.toString.call(itIsAMystery);

That will give you a string like [object Foo] with "Foo" being the constructor (I think) the interesting part. For "native" types (like Date or String) you get back that constructor name.


In my experience, the main problem with typeof comes from distinguishing between arrays, objects, and nulls (all return "object").

To do this, I first check typeof then I check the null case or the "object's" constructor, like this:

for (o in obj) {
    if (obj.hasOwnProperty(o)) {
        switch (typeof obj[o]) {
            case "object":
                if (obj[o] === null) {
                    //do somethign with null
                } else {
                    if (obj[o].constructor.name === "Array") {
                        //do something with an Array
                    } else {
                        //do something with an Object
                    }
                }
                break;
            case "function":
                //do something with a function
                break;
            default:
                //do something with strings, booleans, numbers
                break;
        }
    }
}