Comments' Usage and Best Practices in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

πŸ’¬ Comments

In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program.

In this article, we will learn some of known ways of writing comments, their usages, best practices and more.

Although all of the examples in this article are in JavaScript and it will be according to jsdoc format, the overall idea remains same for any programming language.

πŸ“‹ Table of Contents


πŸ›ŽοΈ Importance

We all know that reading and understanding programs is much more difficult than writing them. And that's why comments are always very useful when it comes to understanding another developer's code.

And believe me, it's not just only for other developers, it's for future yourself, too. After looking at our own code after couple of months, even we sometimes are not sure why we wrote that piece at first place.

Jef Raskin stated importance of comments in his essay of Comments Are More Important Than Code:

The thorough use of internal documentation is one of the most-overlooked ways of improving software quality and speeding implementation.

✍️ Syntax

When it comes to syntax, there are 3 types: Single line, inline and multi-line or block level comments.

1️⃣ Single line

We write these comments with two forward slashes //:

// Single line comment

JavaScript ignores everything immediately following the // syntax until the end of the line.

πŸ“‘ Inline

When we write single-line comments at end of code-line, it's called inline comment.

let s = 'Hello world!'; // assign string literal to variable s

These are used to annotate tiny and very specific snippets of content. Inline comments are more obvious as they are related to the exact line where we write it.

πŸ“„ Multi-line or Block

Multi-line or block comments are written with opening tags /* and closing tags */:

/*
     Line 1
     Line 2
*/

Although above variant is valid, but more standard practice is something like this:

  • it starts with a blank line starting with /**
  • each content line starts with *
  • it ends with a blank line starting with */
/**
 * This can be a description of function.
 * Which needs more space
 * and some extra lines
 */

πŸ‘¨β€πŸ’» Usages

Unlike syntax, usages do not have pre-defined or fix set of categories. Different developers (or commentators) have provided multiple viewpoints on this. So, here I present my viewpoint:

πŸ’Ό Prefacing

In this, developers start each piece of code with a block comment that briefly describes it. This should summarize the purpose of its code. Preface stands as helping hand for developers (sometimes even the one who coded it), who need to understand the code in future. You can write both code and algorithmic description in this.

Take a look at below example:

/**
 * The following program contains the source code for a game called Baghchal.
 * Baghchal is a popular board game in Nepal where two players choose either sheep or tiger. It is played on a 5x5 grid.
 * For the player controlling the tiger to win, they must capture all the sheep. There are altogether 4 tigers on the board.
 * For the sheep to win, all tigers must be surrounded and cornered so that they cannot move. The player controlling the sheep has 20 sheep at his disposal.
*/

πŸ—‚οΈ Metadata

Comments can often store metadata about file or a specific code. In particular, this matedata can help maintainers submit any improvements or fixes to original author, it is very crucial part if your building an open source code base.

/**
 * Represents a book.
 * @author Dharmen Shah <hey@shhdharmen.me>
 * @version 1.2.3
 * @see {@link http://github.com|GitHub}
 * @since 1.0.1
 * @constructor
 * ...
 */
function Book(title, author) {}

Metadata can also be present at file level, it holds data for particular file. See below for example:

/**
 * @file Manages the functionalities of Book.
 * @author Dharmen Shah <hey@shhdharmen.me>
 */

🏷️ Tagging

Generally, there are many keywords used for tagging, TODO: is the one most I use.

TODO: is used when you're planning your code:

/**
 * ...
 * TODO:
 * - [x] get banans
 * - [x] store bananas
 * - count bananas
 * - cut bananas
 * - make smoothie
 * ...
 */

You can also use @todo tag from JSDoc.

Other tag can be one from below:

  • BUG or FIXME – a known bug that should be corrected.
  • HACK – a workaround.
  • UNDONE – a reversal or "roll back" of previous code.

You can work with your team to introduce any new tag. For instance, if I am not happy with current approach of code, I use IMPROVE or IMPROVEMENT NEEDED tag. So that any other developer who visits that code, may think of any other and maybe better approach.

πŸ–¨οΈ Document Generation with JSDoc

JSDoc is the most widely used documentation generator for JavaScript. It generates a well-formatted, ready to publish web project.

For example, when we create a book.js file with below content:

/**
 * @file Manages the functionalities of Book.
 * @author Dharmen Shah <hey@shhdharmen.me>
 */

/**
 * Represents a book.
 * @author Dharmen Shah <hey@shhdharmen.me>
 * @version 1.2.3
 * @param {string} title - The title of the book.
 * @param {string} author - The author of the book.
 * @returns {Object} - The book object itself.
 * @see {@link http://github.com|GitHub}
 * @since 1.0.1
 * @constructor
 */
function Book(title, author) {}

And generate docs with help of JSDoc:

npm i -g jsdoc
jsdoc book.js

It will create a directory named out, and if you browser the files in browser they look like below:

JSDoc output sample

JSDoc output sample

Please checkout it's website https://jsdoc.app/ for more details.

βœ… Dos & ❎ Don'ts

Best practices for comments should be governed by company's development guidelines. Because normative views and long-standing opinions regarding the proper use of comments in source code vary from developer to developer, some can be informal and based on personal preference, while others follow formal guidelines for a particular community.

Having said that, following are some rules I believe should be followed when writing comments.

🌱 Preface - Keep it short

If you're including a preface, it shouldn't be long. It should summarize the description of code. Trust me, no developer wants to read long essay in preface, it should be short, crisp and to the point.

πŸ“‡ Level of detail

Not every time it is required to write a comment. For example, take a look at below:

let d = new Date(); // assign today's date to variable d

Now, above comment would be suitable if you're teaching a beginner level developer. However, this would not be appropriate in the context of production code, or other situations involving experienced developers. Instead, you could write above code in below manner:

let today = new Date();

This not only saves developer from writing comments, but it also makes code self-documenting. We're going to talk about self-documenting code in the last part.

As a side note, the best to declare such references as constants: const TODAY = new Date();, because you don't want to change TODAY's value in rest of your code.

πŸ“› Description beyond the name

The best names for API or function are "self-documenting", meaning they tell you basically what the API does. If your comment just repeats the name, it is not providing more information.

In the ideal comment, content is beyond those words. And comment should be rewarding with some bit of information that was not immediately obvious from the API or function name.

For example, below should be avoided:

/**
 * Sets the tool tip text.
 *
 * @param text  the text of the tool tip
 */
function setToolTipText(text) {}

And below should be preferred:

/**
 * Registers the text to display in a tool tip.   The text
 * displays when the cursor lingers over the component.
 *
 * @param text  the string to display.  If the text is null,
 *              the tool tip is turned off for this component.
 */
function setToolTipText(text) {}

🩳 Avoid short forms

Below is brief list of short forms which should be avoided and instead their full forms should be used:

Short formPreferred full form
akaalso known as
i.e."that is" or "to be specific"
e.g.for example
viz."in other words" or "namely"

βš“ Required Tags

@param and @return tags should be required, even if they're redundant with the description.

πŸ”€ Order of Tags

Include tags in the following order:

  1. Description, @description or @desc
  2. @author
  3. @version
  4. @param - 🚨 Required
  5. @return - 🚨 Required
  6. @exception or @throws
  7. @see
  8. @since
  9. @deprecated

🀐 Swearing or Stress Relief

Sometimes, to relieve stress about development tools, competitors, employers, working conditions, or even the quality of the code itself, developers add comments in a way. The best example for this phenomenon is profanity tracker for linux kernal source code.

We should totally avoid writing such comments. But, that doesn't mean ignore the stress, please consult with respective authority.

Other examples

I always refer to some of best open-source projects to learn the usages and best practices of comments. Angular, Lodash and Bootstrap follow really good practices. For Angular and Lodash, most of their documentation is generated from comments in code itself.

✏️ Editor Support - VS Code

As Visual Studio Code is most widely used editor for JavaScript, let's see how it helps to write and highlight comments.

πŸ€– IntelliSense

In VS Code, you just need to type /** and it will create the closing tag. IntelliSense works for JSDoc tags.

VS Code comments example

πŸ”Œ Plugins

There are plenty of plugins which help developers to write better comments.

Document This is really helpful when you want to generate comments based on your function:

VS Code - Document This example

And these are helpers to highlight comments: Better Comments and TODO Highlight.

VS Code Extension - Better Comments

VS Code Extension - TODO Highlight

πŸ“Ÿ Self-documenting code

It is worth mentioning that apart from comments, there is one more approach: Self-documenting Code. This is also one way to making your code easier to understand for your peer.

Self-documenting code is ostensibly written using human-readable names, typically consisting of a phrase in a human language which reflects the symbol's meaning, such as article.numberOfWords or TryOpen. The code must also have a clear and clean structure so that a human reader can easily understand the algorithm used. Source.

Now, it totally depends on you (and/or maybe your team/company), which one do you like to follow. I would like to highlight a few a differences between comments and self-documenting code:

MatterCommentsSelf-documenting code
⚑EasinessEasySomewhat difficult
πŸ‘¨β€πŸ’»ExpertiseNone requiredSome practice is required
πŸ“ƒDescriptivenessDepends on who is writing itCode is clear, but details can be sometimes missing
⏱️TimingsTime-consuming
A developer needs to write comments after a part of code, so spends more time.
Not time-consuming
A developer writes coding and documenting it simultaneously. But one needs to be careful about structure.

I think self-documenting code comes with practice and a level of expertise is also required. What should be the maximum length of a variable/function name, etc. kind of rules also become necessity in self-documenting.


β›³ Conclusion

We saw and understood usage, dos and don'ts, and editor support for comments in your code. In my experience, it's always better to use combination both, self-documenting code and comments to make your code more readable and dev-friendly.

Let me know if you follow some other best practices and if your team has a totally different approach to do so.

This article is highly inspired from below resources:

Lazar Nikolov's photo

Super insightful! Knowing how to properly comment and document your code is a must-have skill when working in a team.

Dharmen Shah's photo

That's very right. Comments are the most important part, they make the knowledge transfer much smoother between team mates.

Victoria Lo's photo

Wow this is an insightful article! I realized that I'm definitely not commenting in best practices after reading this. Oops..

Dharmen Shah's photo

Yeah... But I am sure you will.