Gadget Development Tip: Lint your JavaScript

If you've written web or Sidebar gadgets, then you know that you write a lot of JavaScript. JavaScript programming can be tricky as it in an interpretive language (i.e. not pre-compiled like other languages such as C). One thing you can and should do to help eliminate JavaScript "gotchas" is to lint your code.

Those of you out there that are current/former C programmers are familiar with lint. Think of lint as a kind of pre-compiler. It looks for things like missing semi-colons, case statements without a break and one of the biggest causes of errors in JavaScript applications: variables that are used by never defined, causing them to be defined globally (i.e. in the window object).

You can find lint utilities for many different languages. A good free JavaScript lint utility (and the one that I use) is called JavaScript Lint (JSL). It doesn't have an install program, so unzip the contents of the download file into the new folder C:Program FilesJavaScript Lint. There are many configurable setting so be sure to read the documentation online.

The cool thing about JSL is that you can integrate in right into Visual Studio 2003/2005 or Visual Web Developer. Just go to Tools, External Tools… and add a new menu item that looks like this:

I've setup Visual Studio so that the current file is linted when I press Alt-L. To set this up, click on Tools, Customize…, Keyboard… and scroll down to Tools.ExternalCommand1 in the listbox on the right. Click in the Press shortcut keys textbox and press Alt-L on the keyboard. Click Assign and OK to save.

If you're one of those people who copy/paste using the mouse, you may want to setup a toolbar button for your new found friend. Select Tools, Customize… and from the Commands tab scroll down to Tools. On the right hand listbox, find External Command 1 and drag it onto your toolbar. Right click on the button and select Default Style. Then right click again and choose either Edit Button Image (if you are the creative type) or Choose Button Image to choose from several lame pre-drawn buttons.

Don't be alarmed if the first time you lint your JavaScript you encounter tons of errors. Writing clean lintable JavaScript is something that takes time to form a habit. You may also look at your code and say "there's nothing wrong with that". For the most part, if JSL finds something wrong with your code, you should fix or rewrite that line.

Linting your JavaScript will help you produce good, clean, error free, cross browser code.