10. Commenting Your Code


In This Chapter

Learn the importance of code comments

Familiarize yourself with the JavaScript syntax for writing comments

Understand good commenting practices


We are almost done with our break. Just one more topic left, and it is a good one! See, here is the thing—everything you write in your code editor might seem like it is intended for your browser’s eyes only:

var xPos = -500;

function boringComputerStuff() {
  xPos += 5;

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

  requestAnimationFrame(boringComputerStuff);
}

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

Your code is often used or scrutinized by other people. This is especially true if you are working in a team with other JavaScript developers. You’ll often be looking at your teammates’ code, and they’ll often be looking at your’s. You need to ensure your code makes sense when someone new is looking at it. 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 you write in your code that communicate something to humans:

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

function sweetRevenge() {
  var blah = true;

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

In this example, the comments are marked by the // character, and they provide some not-so-useful information about the code at hand.

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. You can use comments to mark lines of code that you don’t want executed:

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

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

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

You’ll often find yourself using the code editor as a scratchpad, and comments are a great way to keep track of things you’ve tried in making your code work without affecting how your application ultimately runs.

Single Line Comments

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

You 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;
  }
}

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

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

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

As you know well by now, your comments don’t run as part of your 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 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:

/*
var mouseX = 0;
var 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, you’ll use a combination of single line and multi-line comments depending on what you are trying to document. This means you need to be familiar with both of these commenting approaches.

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 make your 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. Related to the previous point, 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) {
  var selectContent = document.querySelector("#stateList");
  var 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 (var i = 0; i < selectContent.length; i++) {

    var 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.

5. 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.


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.62