Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Detecting types in JavaScript sucks

This answer discusses the standard way to check the type of a JavaScript object (specifically, an array):

The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
    alert( 'Array!' ); }

Why abuse Object.prototype.toString? It turns out that objects created in different frames have different constructors.

typeof only works for objects which are (or have equivalent) primitives, like strings.

Another way?

The above code makes me feel funny inside, and doesn’t have a chance of working for custom types, so I wrote this [Gist]:

function isType(object, type){
     return object != null && type ? object.constructor.name === type.name : object === type;
}

You use it like this:

isType([1, 2, 3], Array);
isType(null, null);
isType('foo', String);

mauke on ##javascript points out that it fails for objects whose constructors have the same name as the type you're testing against:

isType(new (function String(){}), String);

I think I like this behavior more than calling every custom type an Object.

To take it one step further

jQuery has a 25-line isPlainObject to tell if something is a plain object ({ foo: 'bar' }).

In what cases does the jQuery version behave more-correctly than…

isType(thing, Object);

?

Disclaimer: I haven’t tested this code in a bunch of cases or in a bunch of browsers. The experience concentrated into the jQuery source could blow me back to preschool.

share|improve this question
One thing to consider: checking to see whether the constructor names are exactly equal (that is, the exact same string) may not work if it's possible for objects to "drift" between frames. That's one of the reasons that the big libraries don't do things like that -- each window has its own separate "Array" constructor, for example, and it's entirely possible that the name "Array" is distinct window by window also. – Pointy Oct 10 '11 at 4:06
I thought constructor property wasn't reliable in a multi window environment too. – alex Oct 10 '11 at 4:06
isType(false, Boolean) – John Flatness Oct 10 '11 at 4:07
@Pointy: Excellent point. In my testing, comparing the names does work across frames (unlike comparing the constructors themselves). Have you had a different experience? – Sidnicious Oct 10 '11 at 4:11
@JohnFlatness: Thanks! Does this edit fix it? – Sidnicious Oct 10 '11 at 4:13
show 2 more comments

migrated from stackoverflow.com Oct 10 '11 at 10:26

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.