Check if it’s an Object!

×

This post was originally published in 2010
It may contain stale & outdated information. Or it may have grown more awesome with age, like the author.

OK Javascripters, check it out: the IE family don’t like you. Or they love you. I’m not sure. Maybe they just want you to be better? To produce perfect absolutely syntax-error free code. Code that caters for even the most careful pedantic Javascript interpreters.

Example:

In the WYSIWYG text editor we use, when one clicks a UI button that is meant to cause say, an “Embed Flash” dialog to popup, there is a section of Javascript devoted to building said dialog and binding functions, style structure to it. My casual inspection of the code leads me to believe that it stores the dialog as an array of objects and functions. Now, when the dialog is supposed to do it’s popping up, this array is iterated over. Certain things are meant to happen to certain objects, objects with certain properties.

Notice how I said objects there. Objects. Not the functions.

So then, we should test each element to make sure it’s a function, right? Well yeah, we should. But the code wasn’t. Firefox didn’t complain, why would it!? If it’s a function, it won’t have attribute x – it’s a function, dummy! Firefox knows this. Safari does too. The IE family knows ( I guess ), but it wants you to be better ( loves ) or wants you to go insane ( hates ).

See when one of the IE’s hits a function and is asked to test whether it has a property, like this:

if( item.type == 'car' || item.type == 'boat' ){ /* do stuff! */ }

It refuses to cooperate. One is simply told: “‘type’ is null or not an object“.

Helpful!

What it really means, in this case is that IE is too dumb confused and needs you to hold it’s hand.

By hold its hand I mean do something like this:

if( ( typeof( item ) == 'object' ) ){
    if( item.type == 'car' || item.type == 'boat' ){ /* do stuff! */ }
}

First, test to make sure it’s an object! If you’re iterating a structure that contains mixed types, and you want to do something to a specific type, test for the type before diving into type-specific conditionals! It will save your sanity points when it comes time for you, or others when performing browser-compatibility testing.

And if you work on a publicly available project, you’ll be saving other people’s sanity as well ;)

No comments | Trackback