Type Checking With toString() in Javascript

Since Javascript is not a strongly typed language, we need to figure out how to check for variable types. Methods like typeof or instanceof might seem like the obvious answer based on their names, but in most of the cases they’ll give us unreliable results. Specially when comparing against things like objects, arrays or functions which gets a bit trickier without using helper libraries like underscore.

typeof

If we use typeof to check the type of an array variable, the result we’ll get is of type object. And yes, ultimately an array comes from the main Object in Javascript, but we want to know the type of the actual variable, not its ancestor. So usually, typeof is better suited for checking primitives (undefined, boolean, string, number, null) or things that don’t have properties. And even in some cases it can present some problems.

A good use of typeof is to stick to comparing between primitive values or against non primitives. A well known reliable use is to check if a variable is ‘undefined’.

instanceof

instanceof will check between two operands, object and a constructor. It’ll tell us if the left-hand object’s prototype chain has the prototype of the right-hand constructor, kind of like, does this object come from this other one?. Well, since almost every object is derived from the main Object this creates issues when comparing built-in javascript types. Leaving us with better results when comparing custom made objects.

Another known issue with instanceof is that it will only be effective when working in the same iframe, frame , or basically the same DOM environment. Array objects created in a different DOM environments will not share the same constructors. So an object that apparently is the child of another, will end up being unrecognized.

Alternative

A better alternative for type checking is the handy toString method. This method is included in every Object in javascript. toString returns a friendly stringified representation of an object. This returned string in the form “[object Class]” will contain the Class of the passed variable that will help us determine where it comes from.

Note that when checking for arrays, since ECMAScript 5.1 and up provide a method called isArray already, we can check if that method is available first, so we don’t override it.

Number infinity

When looking for numbers I’d like to add an extra layer of verification to make sure the number doesn’t equal the javascript global property Infinity, which is considered a number. So we’ll check if the argument is a number and then make sure we exclude Infinity by using the method ‘isFinite’.

FILE UNDER: