Weekly Chronicles of the Not-so-Obvious: Comment Your Code

Learning how to code in any language is not an easy thing. As a "wanna-be" programmer, I completely understand the struggle of memorizing syntax, forgetting to close brackets and the overwhelming joy that comes from finishing your first, decent piece of code. I work mostly with HTML5, CSS and Javascript, and lately I've discovered the importance of commenting my code.

Here is some mockup HTML code for a web page. You can see we have all the usual elements; head, container, header, footer, etc. At first glance, it's hard to differentiate these parts. Let's try some commenting- for this, we'll just concentrate on the first part of the code, which features the head and header:

So while we have some comments, they're not entirely helpful. I need to be able to easily decipher these sections when looking over the code. We can start by spacing out and labeling each section:

There we go; it's nice to have breathing room. Not only is everything a little spacier, but there's a lot more commenting. The best habit you can pick up is commenting out the end of your divs like I did in the "logo-images" div above. Something ending in '</div>' isn't exactly specific, especially when you end up with more than one at the end of your document:

Gross! What a jumbled mess of confusion. But if we add comments for what the divs actually are:

What a difference! Now we can clearly see where everything ends incase we need to shuffle sections around or insert extra elements. This is also one of those tricks that once you start doing on all of your code, it feels like second nature.

Next time we'll talk about keeping track of your Javascript functions because let's be honest; they desperately need organization.