Comments' Usage and Best Practices in JavaScript
Tags: javascript, comments, jsdoc, bestpractices
Published: 2020-09-11 16:40:13

---
title: Comments' Usage and Best Practices in JavaScript
published: true
description: In this article, we will learn some of known ways of writing comments, their usages, best practices and more.
tags: javascript, comments, jsdoc, bestpractices
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/8a7hvfva91pnte6bs7e0.png
canonical_url: https://blog.shhdharmen.me/comments-usage-and-best-practices-in-javascript
---

# 💬 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](https://jsdoc.app/) format, the overall idea remains same for any programming language.*

## 📋 Table of Contents

- [🛎️ Importance](#importance)
- [✍️ Syntax](#syntax)
  - [1️⃣ Single line](#1-single-line)
  - [📑 Inline](#inline)
  - [📄 Multi-line or Block](#multi-line-or-block)
- [👨‍💻 Usages](#usages)
  - [💼 Prefacing](#prefacing)
  - [🗂️ Metadata](#metadata)
  - [🏷️ Tagging](#tagging)
  - [🖨️ Document Generation with JSDoc](#document-generation-with-jsdoc)
- [✅ Dos & ❎ Don'ts](#dos-and-donts)
  - [🌱 Preface - Keep it short](#preface-keep-it-short)
  - [📇 Level of detail](#level-of-detail)
  - [📛 Description beyond the name](#description-beyond-the-name)
  - [🩳 Avoid short forms](#avoid-short-forms)
  - [⚓ Required Tags](#required-tags)
  - [🔀 Order of Tags](#order-of-tags)
  - [🤐 Swearing or Stress Relief](#swearing-or-stress-relief)
  - [Other examples](#other-examples)
- [✏️ Editor Support - VS Code](#editor-support-vs-code)
  - [🤖 IntelliSense](#intellisense)
  - [🔌 Plugins](#plugins)
- [📟 Self-documenting code](#self-documenting-code)
- [⛳ Conclusion](#conclusion)
  - [🙏 External links](#external-links)

---

## 🛎️ 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.

%[https://twitter.com/alienelf/status/1301061658576642048?s=20]

[Jef Raskin](https://en.wikipedia.org/wiki/Jef_Raskin) stated importance of comments in his essay of [Comments Are More Important Than Code](https://queue.acm.org/detail.cfm?id=1053354):

> 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 `//`:

```javascript
// 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.

```javascript
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 `*/`:

```javascript
/*
     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 `*/`

```javascript
/**
 * 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:

```javascript
/**
 * 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.

```javascript
/**
 * 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:

```javascript
/**
 * @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:

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

You can also use [`@todo`](https://jsdoc.app/tags-todo.html) 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:

```javascript
/**
 * @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:

```bash
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1599808406060/AqftTYgzN.png)

![JSDoc output sample](https://cdn.hashnode.com/res/hashnode/image/upload/v1599808424512/kB4X-WbJU.png)

Please checkout it's website [https://jsdoc.app/](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:

```javascript
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:

```javascript
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const): `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:

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

And below should be preferred:

```javascript
/**
 * 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 form | Preferred full form           |
| ---------- | ----------------------------- |
| aka        | also 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](https://www.vidarholen.net/contents/wordcount/).

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](https://github.com/angular/angular), [Lodash](https://github.com/lodash/lodash) and [Bootstrap](https://github.com/twbs/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](https://cdn.hashnode.com/res/hashnode/image/upload/v1599824523773/jLH7mUGf3.gif)

### 🔌 Plugins

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

[Document This](https://marketplace.visualstudio.com/items?itemName=oouo-diogo-perdigao.docthis) is really helpful when you want to generate comments based on your function:

![VS Code - Document This example](https://cdn.hashnode.com/res/hashnode/image/upload/v1599825129965/Q5E8RBO4d.gif)

And these are helpers to highlight comments: [Better Comments](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments) and [TODO Highlight](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight).

![VS Code Extension - Better Comments](https://github.com/aaron-bond/better-comments/raw/master/images/better-comments.PNG)

![VS Code Extension - TODO Highlight](https://github.com/wayou/vscode-todo-highlight/raw/master/assets/material-night.png)

## 📟 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](https://en.wikipedia.org/wiki/Self-documenting_code#Conventions).

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:

|     | Matter          | Comments                                                                                             | Self-documenting code                                                                                                               |
| --- | --------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| ⚡   | Easiness        | Easy                                                                                                 | Somewhat difficult                                                                                                                  |
| 👨‍💻   | Expertise       | None required                                                                                        | Some practice is required                                                                                                           |
| 📃   | Descriptiveness | Depends on who is writing it                                                                         | Code is clear, but details can be sometimes missing                                                                                 |
| ⏱️   | Timings         | Time-consuming <br> *A developer needs to write comments after a part of code, so spends more time.* | Not time-consuming <br> *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.

### 🙏 External links

This article is highly inspired from below resources:

- [Comment on Wikipedia](https://en.wikipedia.org/wiki/Comment_(computer_programming))
- [Self-documenting code on Wikipedia](https://en.wikipedia.org/wiki/Self-documenting_code)
- [How to Write Doc Comments for the Javadoc Tool](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html)
- [How to make comments the most important ‘code’ you write](https://www.red-gate.com/simple-talk/sql/oracle/how-to-make-comments-the-most-important-code-you-write/)
- [How To Write Comments in JavaScript](https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-javascript)