Maintainable Javascript

Some recent AJAX experimenting and the release of a developer plugin interface for Yahoo! Messenger have led me to dusting off my Javascript knowledge. Particularly with the Messenger plugins (written in HTML with a healthy dose of Javascript), we’ve really seen some poorly written code, both internal and external. I’m starting to put together my own plugin developer guide and have been on the lookout for good articles on the subject.

Christian Heilmann just wrote a great article on Vitamin called The Importance of Maintainable JavaScript:

JavaScript is hip again; there’s no doubt about it. But if you’re starting to get down and dirty with it, there’s no excuse not to keep it clean.

The article describes an 8-step plan to make your scripts more maintainable. They touched on several key concepts, including keeping your scripts self-contained (using namespacing or object literals) and separating textual content from the code itself (making life easier for translation).

I would add to this list the idea of making your Javascript as robust as possible, especially when faced with changing environments or data. A Javascript-enhanced web page or plugin should never cause the dreaded “Javascript error” dialog box to appear. The code needs to be able to handle any unexpected conditions. A common example might be fetching XML data from some other server. If the data is not fetchable or comes back in malformed XML, it needs to be handled cleanly. In my own code, I’m pretty good at testing for object existence before using, but haven’t had much experience with try/catch handling yet.