Commenting Your Code...FTW!

by kirupa   |   filed under JavaScript 101

Everything we write in our code editor might seem like it is intended for our browser's eyes only:

let xPos = -500;

function boringComputerStuff() {
  xPos += 5;

  if (xPos > 1000) {
    xPos = -500;
  }
}
boringComputerStuff();

As we will soon find out, that isn't the case. There is another audience for our code. That audience is made up of human beings.

Our code is often used or scrutinized by other people. This is especially true if you and I are working in a team with other JavaScript developers. We'll often be looking at their code, and they'll often be looking at our code. To make all this code looking as efficient as possible, we need to ensure our code makes sense when someone other than us is looking at it. Even if you are working solo, this applies to you as well. That brilliant function that makes sense to you today might be gibberish when looked at next week.

There are many ways of solving this problem. One of the best ways is by using something known as comments. In this short article, we will learn what comments are, how to specify them in JavaScript, and learn some good practices on how to use them.

Onwards!

What are Comments?

Comments are the things we write as part of our code to communicate something to humans:


// This is for not inviting me to your birthday party!
let blah = true;

function sweetRevenge() {
  while (blah) {
    // Infinite dialog boxes! HAHAHA!!!!
    alert("Hahahaha!");
  }
}
sweetRevenge();

In this example, the comments are marked by the // character, and they provide some questionably useful information about the code being described.

The thing to keep in mind about comments is that they don't run and get executed like all the other code you write. JavaScript ignores your comments. It doesn't like you. It doesn't care what you have to say, so you don't have to worry about proper syntax, punctuation, spelling, and everything else you need to keep in mind when writing normal code. Comments exist only for us to help understand what a piece of code is doing.

There is one other purpose comments serve. We can use comments to mark lines of code that we don't want executed:

function insecureLogin(input) {
  if (input == "password") {
    //let key = Math.random() * 100000;
    //processLogin(key);
  }
  return false;
}     

In this example, the following two lines can be seen in our code editor, but they won't run:

// let key = Math.random() * 100000;
// processLogin(key);

We'll often find ourselves using the code editor as a scratchpad, and comments are a great way to keep track of things we've tried in making our code work without affecting how your application ultimately runs.

Single Line Comments

There are several ways to specify comments in our code. One way is by specifying single line comments using the // mark followed by what we want to communicate. This is the comment variation we've seen several times already.

We can specify these comments in their own dedicated line:


// Return the larger of the two arguments
function max(a, b) {
  if (a > b) {
    return a;
  } else {
    return b;
  }
}

We can also specify these comments on the same line as a statement:

let zorb = "Alien"; // Annoy the planetary citizens

Where we specify comments is entirely up to you. Choose a location that seems appropriate for the comment you are writing.

Since I enjoy sounding like a brokern record, to call out one more time, our comments don't run as part of our application. Only you, me, and possibly Dupree can see them. If that last line made no sense, what you are telling me is that you did not see one of the greatest comedies of our generation. I highly encourage you to put this book or tutorial down and take a few hours to rectify that.

Multi-Line Comments

The problem with single line comments is that you have to specify the // characters in front of every single line you want to comment. That can get really tiring - especially if you are writing a long comment or commenting out a large chunk of code.

For those situations, you have another way of specifying comments. You have the /* and */ characters to specify the beginning and ending of what are known as multi-line comments:

/*
let mouseX = 0;
let mouseY = 0;
 
canvas.addEventListener("mousemove", setMousePosition, false);
 
function setMousePosition(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
}
*/

Instead of adding // marks in front of each line like an animal, we can use the /* and */ characters to save us a lot of time and frustration.

In most applications, we'll use a combination of single line and multi-line comments depending on what we are trying to document. This means we need to be familiar with both of these commenting approaches.

JSDoc Style Comments

When we are writing some code that you want used by others, you probably want an easier way to communicate what your code does beyond having people rummage through source code. That easier way exists, and it is made possible by a tool known as JSDoc! With JSDoc, you slightly modify how you write your comments:

/**
 * Shuffles the contents of your Array.
 *
 * @this {Array}
 * @return {Array} A new array with the contents fully shuffled.
 */
Array.prototype.shuffle = function() {
  let input = this;

  for (let i = input.length - 1; i >= 0; i--) {

    let randomIndex = Math.floor(Math.random() * (i + 1));
    let itemAtIndex = input[randomIndex];

    input[randomIndex] = input[i];
    input[i] = itemAtIndex;
  }
  return input;
}

Once you have commented your files, you can use the JSDoc tool to export the relevant parts of your comments into an easily browseable set of HTML pages. This allows you to spend more time writing JavaScript while giving your users an easy way to understand what your code does and how to use various parts of it.

If you want to learn more on how to use JSDoc, check out their awesome Getting Started page for more details.

Commenting Best Practices

Now that we have a good idea of what comments are and the several ways we have to write them in JavaScript, let's talk a bit about how to properly use comments to help make our code easy to read:

  1. Always comment your code as you are writing it. Writing comments is dreadfully boring, but it is an important part of writing code. It is much more time efficient for you (and others) to understand what your code does from reading a comment as opposed to reading line after line of boring JavaScript.
  2. Don't defer comment writing for later. Deferring comment writing for a later time is the grown-up equivalent of procrastinating on a chore. If you don't comment your code as you are writing it, you'll probably just skip commenting entirely. That's not a good thing.
  3. Use more English and less JavaScript. Comments are one of the few places when writing JavaScript that you can freely use English (or whatever language you prefer communicating in). Don't complicate your comments unnecessarily with code. Be clear. Be concise. Use words.
  4. Embrace whitespace. When scanning large blocks of code, you want to ensure your comments stand out and are clear to follow. That involves being liberal with your Spacebar and Enter/Return key. Take a look at the following example:
function selectInitialState(state) {
  let selectContent = document.querySelector("#stateList");
  let stateIndex = null;

  /*  
      For the returned state, we would like to ensure that
      we select it in our UI. This means we iterate through
      every state in the drop-down until we find a match. 
      When a match is found, we ensure it gets selected.
  */

  for (let i = 0; i < selectContent.length; i++) {

    let stateInSelect = selectContent.options[i].innerText;

    if (stateInSelect == state) {
      stateIndex = i;
    }
  }

  selectContent.selectedIndex = stateIndex;
}

Notice that our comment is appropriately spaced to distinguish it from the rest of the code. If your comments are strewn about in arbitrary locations where they are difficult to identify, that just unnecessarily slows you and whoever is reading your code down.

  1. Don't comment obvious things. If a line of code is self-explanatory, don't waste time explaining what it does unless there is some subtle behavior you need to call out as a warning. Instead, invest that time in commenting the less obvious parts of your code.

The best practices you see here will take you far in ensuring you write properly commented code. If you are working on a larger project with other people, I can assure you that your team already has some established guidelines on what proper commenting looks like. Take some time to understand those guidelines and follow them. You'll be happy. Your team will be happy.

Conclusion

Comments are often viewed as a necessary evil. After all, would you rather take a few minutes documenting what you clearly already know, or would you rather implement the next cool piece of functionality? The way I like to describe comments is as follows: It is a long-term investment. The value and benefit of comments is often not immediately obvious. It becomes obvious when you start having other people looking over your code, and it becomes obvious when you have to revisit your own code after you've forgotten all about it and how it works. Don't sacrifice long-term time savings for a short-term kick. Invest in single line (//) and multi-line (/* and */) comments now before it is too late.

If you have a question about this or any other topic, the easiest thing is to comment below or drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )

WHAT'S ON YOUR MIND

HOT FORUM TOPICS

Serving you freshly baked content since 1998!

Killer hosting by (mt) mediatemple

Facebook Twitter Youtube Pinterest Instagram Github
BACK TO TOP
new books - yay!!!