JavaScript summed up #3: Type checking
Since JavaScript currently is a dynamically typed language, the topic of type checking is quite interesting. In certain situations it’s rather important to know of which type the object at hand really is.
Here, we have some dummy objects that we want to type-check:
var num = 12;
var string = "Hello World";
var array = [1,2,3];
var object = { firstProp: 1, secondProp: 2 };
function Car(){};
var car = new Car();
Let’s look at two different ways to check the type of an object.
typeof
With the help of the typeof keyword, you have one possibility to check an object’s type. An example usage could look like this:
if ( typeof num == "number" ) ... // true if ( typeof array == "array") ... // false, because "object" is returned if ( typeof car == "Car" ) ... // false, because "object" is returned
The typeof way works nicely with most object types. But unfortunately, it leaves a little uncertainty when dealing with types like Array or your own types (like “Car” in our dummy examples). That’s because typeof only returns the not so helpful “object” in those cases. So let’s look at another way…
constructor
Every JavaScript object has a property called “constructor” – which proves to be helpful in our case:
if ( car.constructor == Car ) ... // true if ( array.constructor == Array ) ... // true
The constructor-variant has the advantage of returning a reference to the function that was used when creating the object in question – not just “object”. Since a reference is returned, you have to remember not to use quotation marks (in contrast to the typeof variant, where a string is returned).





2 comments
cool cool cool cool cool cool cool cool
This almost works, except when your Array comes from a different document, e.g. try calling alert(parent.someArray.constructor == Array) from an iframe (assuming you declared someArray in the parent page).
A more robust solution (which is used in places like jQuery core, for example):
if (Object.prototype.toString.call(theArray) == “[object Array]“) {…}
Leave a Comment