How to Comment Code: Best Practices & Examples

Commenting code is almost always considered bad practice.

A common excuse to comment on code is to improve poorly written code. This is a mistake most beginners or even advanced developers make.

Instead of commenting on code, rewrite it!

The code should always be clear enough to express itself.

On rare occasions, however, code comments are necessary.

This guide teaches you the best practices for leaving and not leaving comments in your code. After reading this guide, you understand when using and not to use comments.

The theory is backed up with examples. In this guide, we use JavaScript. However, the language does not really matter as these rules apply in programming in general.

Why Code Comments Are Bad?

In an ideal world, the code should always be clear enough to express itself. If you write the code in a clear and descriptive manner, you do not need comments.

In other words, you should avoid writing comments.

The problem with comments is that you need to maintain them too. When you change the logic, you need to remember to update the relevant comments. This causes a lot of unnecessary overhead.

In this sense, almost any code comment is bad. In general, a code comment is bad if it:

  • Is not needed.
  • Explains bad code.
  • Requires maintenance.
  • Is an out-commented piece of code.
  • Is used as a visual marker.
  • Is used as a Todo action.

What Is a Useful Code Comment?

As you learned, code comments are rarely useful. However, on some rare occasions, comments are necessary.

A code comment is useful only if it:

  • Clarifies out-of-sort code that is needed for business purposes.
  • Is used to disclose the legality of the piece of code.

Basically, in all other cases, code comments are bad.

Best Practices to Leave Meaningful Comments

To put it in one sentence, avoid code comments altogether. Use them only if they are absolutely necessary.

Here are the best practices related to commenting code.

1. Do Not Duplicate the Code with a Comment

Beginner coders tend to write a bunch of comments. In some programming courses, commenting code is even recommended.

This is because as a beginner, code comments may help you understand your code a bit better.

But as you gain more experience, the comments become less helpful.

Avoid writing comments that repeat the code!

For example, this is a useless comment:

i = i * 2 // Multiplies the original value of i by 2

This comment provides no additional information nor does it clarify the code. Instead, it only repeats the code.

2. Do Not Use Comments to Hide Unclear Code

A common misuse of a code comment is to add information that should live in the code.

For instance, take a look at this piece of JavaScript:

// An array of names
let a = ["Alice", "Bob", "Charlie"]

// n is the name, a is the array of names
for (n of a) {
    // display the name
    console.log(n)
}

These comments could have been avoided by using better variable naming conventions.

Let’s update the variable names to be more descriptive:

let names = ["Alice", "Bob", "Charlie"]

for (name of names) {
    console.log(name)
}

After improving the variable names, the comments become unnecessary. The code now expresses itself clearly enough.

Do not explain bad code with comments. Instead, rewrite the code.

3. Only Write Comments as You Code

Leave the comments as you write code.

It is tempting to write all the code first and then add the comments. But if you add comments retrospectively, you can easily forget what to include. This leads to useless and uninformative comments. Worse yet, this can lead to a comment missing altogether.

4. Add Links to the Origin of Copied Code

Every so often you find a valuable piece of code online.

If you decide (and have rights) to use this code in your project, add a link to the source. This helps the future readers get the full context.

For example, let’s use an email validation script from Stack Overflow:

// Validates email addresses. Source: https://stackoverflow.com/questions/46155/how-can-i-validate-an-email-address-in-javascript
const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};

If you encounter this kind of code in your codebase, you may wonder what it does. The expression is rather verbose and there are lots of moving parts. This may even lead you to wonder whether the code actually works or not.

A simple comment with a link to the resource helps give a full context easier than you trying to explain it.

5. Do Not Leave “To-Do” Comments

In programming, to-dos are tasks for the future.

Keeping track of to-do items is useful, but the codebase is not the right place to do it.

Do not live this kind of comment to the codebase:

// TODO: Enable user authentication in the future

One problem is you need to keep them up to date.

Also, chances are the to-do is accidentally left hanging in the codebase. When another developer looks at a to-do item, they might implement it. But if you have implemented it already, that is going to be double work.

6. Do Not Comment Code “Out”

Do not “comment out” code that “could be useful in the future”.

An out-commented piece of code causes confusion. The future reader may wonder:

  • Why is the code commented out?
  • Should this not be commented out?
  • Should I delete this code?

If a piece of code is not in use, delete it. Do not leave it hanging in the codebase as a comment.

If you need the out-commented code in the future, you should use version control.

This is one of the countless benefits of version control. You can travel back in time to inspect and revive old pieces of the code if needed.

7. Do Not Use Comments as Visual Markers

Especially as a beginner, you may have a bad habit of marking areas of code with comments.

For example:

// ------ CONSTANTS ------
const pi = 3.142
const e = 2.712

// ------ VARIABLES ------
let x = 10.0
let y = 20.0

// ------ FUNCTIONS ------
function areaCircle(r) {
    return pi * r * r
}

function volumeSphere(r) {
    return (4 / 3) * pi * r * r * r
}

These visual marks take a lot of space and they are completely useless.

You should not use comments to visually mark or otherwise decorate the codebase. It will only cause confusion and overhead for future readers.

If you have a lot of code and need visual markers, split the code into multiple files. Nevertheless, do not use visual markers!

8. Use a Comment to Share “Insider Information”

Sometimes a piece of code might seem useless or out-of-place. The natural reaction to this is to remove the piece of code.

But what if the expression is not a mistake?

It is quite common for larger projects to have to cover some “edge cases” with smelly code.

To avoid silly mistakes, it is wise to leave a comment that shares the “insider information” the developer needs to know.

function getDomain(email) {
    // Our email database uses "(at)" instead of "@" in email addresses.
    return email.split("(at)")[1]
}

Take a look at the above code. It seems there is a mistake. Instead of splitting the email by the character “@”, “(at)” is used.

But luckily, there is a comment that clarifies the logic. Now a developer does not accidentally change this logic.

9. Use a Code Comment to Disclose Third-Party Code

When you use open-source libraries, you might need to add a legal note at the top of the file.

This depends on the license of the code in question. If the license orders you to add a legal note, you must do so. There is no way around it.

In a sense, a legal note is the only example of truly useful comment.

Last but not least, let’s see an example of some code with unnecessary comments.

Example 1: Removing Bad Comments & Improving the Code

Here is a piece of JavaScript code that finds the largest number in an array.

// Gets biggest numbers in a list
function biggestNum(arr) {
    // Initialize the candidate number to a smallest value possible
    let num = Number.NEGATIVE_INFINITY
    
    for (let i = 0; i < arr.length; i++) {
        // Check if the current number is greater than the candidate
        if (arr[i] > num) {
            num = arr[i]
        }
    }
    
    // Return the candidate number.
    return num
}

As you can see, there are a bunch of comments in this piece of code.

The truth is none of these comments are helpful. Instead, we can use better naming conventions to get rid of the comments.

Here is the non-commented version:

function getBiggestNumber(numbers) {
    let biggestSoFar = Number.NEGATIVE_INFINITY

    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] > biggestSoFar) {
            biggestSoFar = numbers[i]
        }
    }

    return biggestSoFar
}

So what did change?

  1. The function name biggestNum does not express itself. Because we want it to return the number, it makes more sense to call it getBiggestNumber.
  2. num = Number.NEGATIVE_INFINITY is confusing. What the heck is the num? With a bad variable name like this, it definitely needs a comment. But when you change the name to biggestSoFar, the meaning becomes obvious.
  3. In the if-statement, comparing numbers[i] with biggestSoFar is more obvious than comparing num with arr[i].
  4. Commenting on the return statement makes no sense. It is explicit and clear enough that the function returns the biggest number.

As you can see, not a single comment is needed in the above piece of code. It is best to focus on code clarity instead of writing comments on it.

Conclusion

Commenting code is bad practice.

You should not comment code unless absolutely necessary.

Do not use comments to explain poorly written code. Re-write the code instead.

Bad examples of comments include:

  • Out-commented code
  • Todo items
  • Visual markers that split the code into sections
  • Comments that duplicate code

One of the only useful situations in which code comments are useful is sharing domain knowledge. A useless-looking piece of code that has an important meaning should be clarified with a concise comment. This way you avoid the risk of someone accidentally deleting the piece of code.

Also, sometimes when you are not the owner of a piece of code, you should add a legal note at the top of the code file.