Archive

Anyone who has written more than a handful of lines of Javascript has found a need to find out the type of a variable. A quick search on their favorite search engine or in their reference book turns up typeof, which indeed tells you the type of a variable. It works great, except if you’re looking for arrays, null, or NaN.

This type of test works well for strings, numbers, functions, and undefined. You most often see it used for the first three of these. Most people check for undefined more directly:

if( something === undefined){
// treat it like it isn't defined
}

This is particularly useful if you are wanting to know whether an argument for your function was included when the function was called.

var myfunction = function(foo){
if(foo === undefined) foo = "bar";
// now we can do something with it, knowing that it is defined.
}

So, what do you do if you have a variable that might be an array or an object, and you need to know which it is? Using typeof doesn’t help, because it tells you that it’s an object either way. It is an object either way, actually, but that’s not very helpful.

The easiest test between a non-array object and an array is by checking for length. Arrays have a length, non-array objects do not. So if typeof says its an object, and its length !== undefined, then it is an array.

NaN is a special confusing case. NaN is a value representing “Not a Number,” except that of course typeof says that NaN is a number. It is useful for working with messed up math and bad dates, both of which are best detected as quickly as possible. NaN is returned by several Javascript methods such as parseFloat and parseINt. NaN is never equal to any number, including itself. So to test for NaN you use the aptly named isNaN(testValue), which returns true if testValue is indeed not a number.

Putting all this in a simple function that you can use to find the type of something is fairly easy:

If there’s a law against abusing the ternary operator anywhere, that is sure to break it.

One other thing worth noting about testing variable types is testing booleans. Using typeof we get “boolean” as the response if the operand is actually (===) true or false. So the following variables are all boolean, according to typeof: