Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

JavaScript Comments

Chapter 7 13 mins

Learning outcomes:

  1. What are comments
  2. Creating single-line comments using //
  3. Creating multi-line comments using /* */
  4. Tips for writing comments

What are comments?

Let's imagine a scenario.

You create a tedious and complicated program with tons and tons of intricate details. You code it for over a week, before finally completing it, and then continuing on with another project.

After a long span of one whole month, you return back to this program, wanting to add some new bells and whistles to it. However, what happens ahead is something surprising. You just couldn't make sense of what's happening in the code — code that you wrote all by yourself!

But why is this so?

Well, it's human nature to forget things if not revisited on a regular basis.

In the case above, you wrote some code and then left it unattended for almost a month. This time lag led to all the nice memory cells built in your mind, to keep track of the program's code, to fade away slightly, if not completely.

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. However, as you might agree, this ain't practical at all, given that we might have other projects to focus on as well.

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 is, to 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 come back to the code after a long span of time in between, we can still make sense of it in a very short amount of time.

This is exceptionally amazing.

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

Not only this, but comments are used in programming for documentation purposes as well, that is to describe the syntax and semantics of code. In the sections below, we'll see how to document JavaScript code.

Sometimes, comments are also used while testing a given program. Without comments, we'd have to delete irrelevant segments of code while we are testing others. But with comments, the irrelevant segments can be kept right there in the code, and just 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 forward slashes (//) are used to denote a single-line comment in JavaScript. The text of the comment follows the slashes, as shown below:

// This is a single-line comment.

The comment can appear even after a statement, as follows:

var x = 10; // This is another comment.

Moreover, we can have as many comments in a program as we want to:

// This is a comment.

var x = 10; // This is another comment.

// Another one.
var y = 30; // And another one.

console.log(x + y);

The limit is only the imagination.

Moving on, as the name suggests, a single-line comment only extends up to the end of the line it's 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 won't be parsed as a comment but instead as actual code and, since it usually isn't grammatically valid, would eventually 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 the comment on the next line, we can either use multiple single-line comments, as shown below:

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

Or we could 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 following the comment being parsed as part of the comment.

Shown below are two simple examples.

First, for the comment being parsed as actual code:

/ * This is a comment */

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

Surprisingly, the typo we made didn't lead to an error — rather, it led to another value in JavaScript, without us even realizing it! This is an instance of the comment being mistakenly parsed as code because we weren't careful in typing /*.

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 code being mistakenly parsed as part of the comment:

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

var x = 10;

Due to the mistyped */ in line 1, the comment doesn't terminate in line 1 and instead, continues over to the end of the script.

If we go on to execute this code, obviously the code won't run, but the error raised might be described differently depending on the browser being used.

For instance, in 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.

If Chrome isn't able to find a corresponding ending pair for /*, it doesn't consider the line containing /* as a comment at all, and raises an error saying that it's syntactically invalid.

Anyhow, one thing is clear by this point — if there is a clerical error in writing /* or */, there can be unexpected outcomes in our programs. Likewise, we must always write these very 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.

var x = 10;
var y = 20;

console.log(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 a 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 following each of them 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 redundant.