views:

106

answers:

4

What's it used for if it always returns "object" as type?

--update

always for Elements or lists.

+1  A: 

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.

Pointy
*... with "Foo" being ...* the value of the `[[Class]]` internal property, which represents - *for native objects* - a specification defined *classification* -not really a *type*!- and for host objects it basically could be anything....
CMS
Wow thanks @CMS!
Pointy
+1  A: 

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.

Spudley
A: 

You have to understand that the type system in JavaScript is dynamic with a few "primative" types to build upon. By treating all complex objects as the type "object" this allows you to duck-type and call methods without necessarily having to know the type of the object being passed around assuming that type has the function call implemented. In a dynamic programming language everything is an "object".

Achilles
A: 

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;
        }
    }
}
AutoSponge