Testing Type

This is the third post in the series 5 Things Everyone Could Learn from the jQuery Source:

3) Testing Type

As discussed above, making sure that the type of our objects is correct goes a long way towards building better code. Sometimes, we need to do a test to make sure that a variable is the correct type before we take an action on it. This could happen in cases where we don’t have full control over things like user input (and honestly, who DOES have full control over user input? Users don’t even have full control over what they input), or when a function may return different data types depending on the results of its internal processing. In a case like this, we need a reliable way to test what the type of our variables is. Although it happens in other places before this, I’m going to pick line 3944 and the following code as my example:

} else if ( typeof val === "number" ) {

This is using the JavaScript ‘typeof’ operator to return what the type of the variable ‘key’ is. The typeof operator in JavaScript returns a string. And in this case we are going to use the explicit equals (===) to test whether the string that comes back from typeof is equivalent to the string “object”. If they are explicitly equal (aka, both a string and both with the value ‘object’) then we can proceed on with our work because we know, without a shadow of a doubt, that any work we do on ‘key’ can be done using object methods and techniques. This is also good for testing things like ‘undefined’. Separate from null (discussed above), you can test whether something is “undefined” by doing this:

if (typeof some_var === "undefined")

This will let you know whether or not a variable has even been defined, which can be incredibly useful in keeping your code from erroring out due to a missing variable declaration, or trying to do something on a variable that doesn’t exist yet. It’s a great test to make your life easier…and it makes your code easier to read for everyone that has to come afterwards and either maintain or (hopefully) extend it. I use this a lot when I have a script that runs on multiple pages, but only one or two of those pages are setting a variable which might change the way my script runs. In those cases, I use this typeof test for undefined to determine whether that variable has been set at all.

Published 6 Feb 2011

Writing better code by building better JavaScript
Don Burks on Twitter