What are comments?

Let's imagine a scenario. We write a tedious and complicate program with tons and tons of intricate details and then after completing it, continue on with another project.

Then after a long span of one whole month, we return back to the code wanting to add some new bells and whistles. However, what happens ahead is something truly not anticipated. We just couldn't make sense of what's happening in the code — code that we wrote all by ourself!

But why is this so?

Well, this isn't really surprising. It's human nature to forget things if not revisited on a regular basis. In our case, we wrote some code and then left it unattended for almost a month. This time lag simply leads to all the nice memory cells built in our mind to keep track of the code to fade away slightly, if not completely.

We just couldn't understand why we named a given function the way we have named it; we couldn't understand why are there seven variables created inside the function on line 80; we couldn't understand what is the purpose of the global constant on line 7; and so on and so forth.

The question that stands is: how to prevent all this from happening?

Well, one option is to keep revisiting the code again and again on a consistent basis, why as you might agree is impossible given that we might have multiple other projects to focus on.

The ultimate solution is to use comments.

At the core:

A comment is a piece of code that's ignored by the parsing engine.

It's merely there to explain code — that, provide sufficient details as to why something happens and exactly how it happens.

When we comment our code, we simply add details for given segments of the code that explain why we're doing what we're doing. This has the benefit that if we forget about the intuition behind the code and then resume to it back again after a while, we can still make sense of it in no time.

This is exceptionally amazing.

Better yet, they can even help other people reading our code to quickly and better understand it.

Sometimes, comments are also used in the debugging stage of a program's testing, turning off certain statements (by commenting them) until some other statements are being tested.

Without comments, we'd have to delete the irrelevant segments of code while we are testing others. But with comments, the irrelevant segments can be kept right there in the code, commented out in order to get the parser to silently ignore them.

Once again, amazing.

So now that we know what exactly are comments, it's time to see how to write them in JavaScript.

How to comment in JavaScript?

There are essentially two ways to write a comment in JavaScript:

  1. A single-line comment using //
  2. A multi-line comment using /* */

Let's start with a single-line comment.

Two slashes (//) are followed by the text of the single-line comment, as shown below:

// This is a single-line comment.

As the name suggests, a single-line comment only extends up to the end of the line its written on. That's why it's called a 'single-line' comment.

For instance, we can't just press Enter while typing the text of the single-line comment. The next line following the one with // (at the start) would be parsed as actual code and, since it usually isn't in the correct grammar, would lead to an error.

An illustration follows:

// This is a single-line comment
that we wish to extend on to the second line.
Uncaught SyntaxError: Unexpected identifier

To extend the text of comment on the next line, we can either use multiple single-line comments or one large multi-line comment.

In the example below, we use two single-line comments to express one single sentence.

// This is a single-line comment
// that we wish to extend on to the second line.

Another way to express this multi-line sentence is to use a multi-line comment.

A multi-line comment is denoted using /* */. The text of the comment goes within the pair of symbols /* and */.

Here's an example:

/* This is a multi-line comment
that we wish to extend on to the second line,
and even to the third line. */

While writing a multi-line comment, make sure to denote the starting /* and the ending */ properly — failing to do so can lead to unexpected consequences such as the comment being parsed as actual code or the code after the comment being parsed as the comment's text.

Shown below are two simple examples.

First, for the comment being parsed as actual code:

/ * This is a comment */

In the code above, we intend to write a comment, however what's denoted is a regular expression literal with the pattern * This is a comment * (between / /).

A regular expression literal is denoted by the same two forward slashes (//) that are used to denote a single-line comment. The only difference is that in a regular expression literal, some pattern is placed between the slashes, and that's how the parser is able to distinguish between a single-line comment and a regular expression literal. We'll see more about regular expressions in the JavaScript Strings unit.

And second, for the comment taking over the code following it, due to the ending */ being written improperly:

/* This is a comment that was supposed to end here. * /

var x = 10;

If we execute this code, the outcome depends on the browser being used.

For instance, on Firefox, we get a syntax error saying that the comment is unterminated. However, in Google Chrome, we get a syntax error saying that there is an unexpected token at the end of the first line of the comment.

Anyhow, one thing is clear by this point — if there is a clerical error in writing /* or */, there can be unexpected outcomes of our programs. Likewise, it's best to write these carefully.

Tips for writing comments

Knowing what comments are, doesn't necessarily tell one how to write good comments. Commenting, just like variable naming, is another art that comes with experience, time and skill.

Below are a couple of tips to consider to write pretty good comments.

Follow a convention

In languages such as JavaScript where we have two ways to write comments, there are conventions devised over the years to help one decide which method to use to write a comment.

The convention of JavaScript is a simple one and quite a standard one:

  1. Use /* */ for documenting code. Documenting means to describe the purpose of a file, a function, a class, a method and so on.
  2. Use // for explaining code. Explaining here means to tell what a statement, or group of statements, does, and maybe even how it does it.

For example, consider the imaginary example below:


* Program 1
* Add two numbers and print the result.

$x = 10;
$y = 20;

echo $x + $y;

Right at the top of the file, we document the name and purpose of the file using the /* */ comment, that is, it's the first program that serves to add two numbers and print the result.

Since the actual code is extremely simple, there really is no need for a // comment to explain the meaning of any statement(s).

Shown below is another example:

 * Approximation of PI using Liebniz Formula.
 * 1 - 1/3 + 1/5 - 1/7 + 1/9 + ... = π/4

// The length of the series.
var iterations = 100;

var sum = 0;
var denom = 1;
for (var i = 0; i < iterations; i++) {
   sum += (-1) ** i * 1 / denom;
   denom += 2;

// sum is equal to π/4
// likewise we have to multiply by 4 to obtain π.
var pi_approximation = sum * 4;


As before, right at the top of the file, we have a simple comment to explain what's happening in the file — computation of π through the Liebniz-Madhava series. Then in the code that follows, we have two // comments to explain what the statement succeeding the comment is doing.

The code above will become much clearer as we progress through this unit.

Break long comments into multiple lines.

Writing long comments is not something surprising in complex applications. Sometimes even in the simplest applications, a short brief license notice, or copyright disclaimer put at the top is considerably long.

Putting long comments on one single line is not syntactically invalid — just not pleasing to the eye. Let's see how.

Below we construct a really long comment that spans a single line:

// This is a long long long comment that takes a long long span of words which is undesirable in JavaScript and all programming languages.

var x = 10;

See how the comment unnecessarily acts as a divider in the code instead of improving its readability by explaining the following statements. It distracts our reading flow on the code, and seems as if though it's not part of the code.

In this case, the example might not look that weird but if you type the code above in your editor that covers the whole screen, you'll find the comment extending out till the end of the screen, and looking extremely awful!

What one should do is break the comment into multiple lines, each one a comment on its own.

The code above can be rewritten in the following way:

// This is a long long long comment that takes a long long
// span of words which is undesirable in JavaScript and all
// programming languages.

var x = 10;

Try to be concise

Writing comments is useful to the programmer and others reading the code. However, writing redundantly long comments with a lot of unnecessary text can backfire — they can make code difficult to read.

When commenting code, try to be as concise as possible. Try to very briefly and neatly express the intent of the concerned piece of code.

Here's an example:

var score = '84';

// Here I am trying to convert score to a number.
score = Number(score);

The comment is clear and undoubtedly explains the purpose of the statement in line 5. However, it contains too much detail.

A much better comment would be the following:

var score = '84';

// Convert to number.
score = Number(score);

A long sentence condensed down to just three words, yet the underlying meaning is still intact.

Cool, isn't this?

Don't comment everything

Remember one rule of thumb: less is more!

Only comment those parts of a program that involve something that's not apparent, i.e. something that would be difficult to understand later on.

Commenting redundant pieces of code as shown below is useless:

var x = 10;
var y = 30;

// Log the sum of x and y.
console.log(x + y);

In line 5, we can easily see that we are trying to log the sum of x and y, and so the comment is more than just useless.