Clever comments

In the newest issue of A List Apart, print style sheets are the order of the day. My good friend and supremely talented DOM Scripter, Aaron Gustafson has written an article called Improving Link Display for Print.

He uses some clever DOM Scripting to turn the hrefs of links into footnotes. The JavaScript is fairly involved and requires the use of some ready-made functions that can be used and reused in situations such as these.

I really like the way that Aaron first sets out what he’s going to do in plain English before moving on to the JavaScript. This is something I do throughout the book. First, plan and write out all the steps that your function needs to take. Then, translate from English to JavaScript.

Aaron has done something really clever. He writes his English steps as comments. Then, as the function gets written, he adds the appropriate JavaScript under the appropriate comment.

So, you might start with just the name of a function and some comments:

function beAnnoying() {
// First, do some object detection
// Next, pop up an annoying message

Then, add the JavaScript for each step:

function beAnnoying() {
// First, do some object detection
if (!document.getElementById) return false;
// Next, pop up an annoying message
alert('hey, hey, hey!');

This is the perfect way to document procedural code. It helps you when you’re writing the code, it helps you when you come back to the code, and it helps anyone else that needs to look at your code.

That’s smart. I wish I had thought of it.

Posted by Jeremy on Wednesday, September 21st, 2005 at 2:30am


Awww, don’t feel bad, it happens to the best of us. I know I’ve looked back on projects and thought the exact same thing.

Looking forward to getting your book in the mail! ;)

# Posted by !!blue on Friday, September 23rd, 2005 at 8:48pm

I’m glad you appreciated that aspect of the article. Personally, I always feel a little slighted when I read an article about a great little script and there is no explanation whatsoever as to what the thought process is behind the code. IMHO, that is half of the learning value of an article or tutorial and it is something I always try and account for in my writing. I’m glad it didn’t go unnoticed.

As an aside, I recommend keeping these comments in your working version of every script, removing them only for the production version (along with any unnecessary whitespace).

# Posted by Aaron Gustafson on Saturday, September 24th, 2005 at 7:38pm

Sorry. Comments are closed.

September 2005

Recommended Reading

XML Subscribe

Grab the RSS feed for this blog.

JavaScript API

Grab the RSS feed of comments for this entry.