Commenting Code in JavaScript - Types and Best Practices

Introduction

The main purpose of writing code is so that a computer can interpret it as commands. However, it's also important that the code we write is also easily interpretable by fellow developers.

Have you ever gone back to a project and had difficulty understanding the internal logic? Well that's probably because said project hasn't been commented properly.

Comments are notes written in the code that are ignored by the JavaScript engine, which means they don't affect the output in any way. Their sole purpose is describing how and why code works to other developers, and yourself.

In this article, we will look at how to comment JavaScript code, as which types of comments exist, and some best practices.

Single-Line Comments

Single-line comments are generally used to comment a part of the line or full line of code. Single-line comments in JavaScript start with //. The interpreter will ignore everything to the right of this control sequence until the end of the line.

Let's see an example of a single-line comment in action:

// Print "Hello World" in the console
console.log("Hello World");

Here, we are using a single-line comment to describe what the next line of code is doing.
If a single-line comment appears at the end of a line of code, it's called an inline comment.

These are generally used to add quick annotations:

let c = a + b; // Assign sum of a, b to c

Multi-Line Comments and JavaScript DocStrings

If we'd like to add a note that is spread across multiple lines, we can opt for multi-line comments or block-level comments.

Multi-line comments start with /* and end with */:

/* The following program contains source code for a game called Tic-tac-toe.
It is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. 
The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner
*/

Here, a multi-line comment is used to describe tic-tac-toe. Generally, multi-line comments are used to introduce and explain a section of code, where a single line/sentence isn't enough.

Another type of multi-line comment can oftentimes be seen as well:

/**
* The following program contains source code for a game called Tic-tac-toe.
* It is a paper-and-pencil game for two players, X and O, who take turns marking the
* spaces in a 3×3 grid. 
* The player who succeeds in placing three of their marks in a horizontal, vertical, or 
* diagonal row is the winner
*/

Oftentimes, these comments can include information about the proceeding code, such as the parameters of a function or even the author of the code:

/**
* Function that greets a user
* @author   John
* @param    {String} name    Name of the user
* @return   {String}         Greeting message
*/
function greetUser(name) {
    return `Greetings, ${name}!`;
}

These comments are referred to as DocStrings, as they're essentially strings (comments) that constitute the documentation of your code.

These types of comments are really useful for other developers in your team, as you can clarify what the expected input is, what the output is, as well as who to contact if need be.

An added benefit is that you can generate documentation based on these DocStrings.

Using Comments for Debugging

Besides making notes, comments can also be used to quickly prevent code execution for debugging purposes. This is possible because JavaScript Engines do not interpret commented code. This is called as commenting out code.

If there's an erroneous line, that's causing problems, we can simply "comment it out" to disable it, without deleting the line. This can be paired with actual debuggers to help you assess what's going on.

Consider the following code:

console.log("Working code");
console.log("Erroneous code);

If we'd like to remove the second statement, but don't wish to delete it forever, we can simply comment it out:

console.log("Working code");
//console.log("Erroneous code);

Pro Tip: In most of the code editors, we can use the keyboard shortcut Ctrl + / for Windows and Cmd + / for Mac to comment out a single line of code.

Additionally, you can also comment out entire sections if you're unsure whether you'll delete them or not:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

/*console.log("Entering for loop");
for (let i = 0; i < 100; i++) {
    console.log(i);
}*/

Good Commenting Practices

First of all, commenting is not an excuse to write unreadable code, and then just patch it up with five paragraphs of comments explaining it. We first have to focus on writing clean, self-explanatory code, which can later be improved with constructive comments.

Use comments to explain why you did something, not how you did it. If you find yourself explaining how you did something, then it's time to take a step back and refactor your code into something self-explanatory.

Another piece of advice would be to not write comments which are obvious and are redundant by nature. For example, the following comment is completely unnecessary:

// Prints out the result
console.log(result)

There are useful tools, such as JSDOC 3 that can generate documentation, based just on the comments within your code, which are formatted as DocStrings outlined above.

Conclusion

In this article, we have gone over what comments are and how to create them in JavaScript. We have looked at different types of comments - single-line and multi-line comments, as well as mentioned JavaScript Docstrings.

We've also seen how to debug our code using a technique called "commenting out", and finally summed up some good commenting practices.

Last Updated: September 22nd, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Abhilash KakumanuAuthor

Hey, I am a full-stack web developer located in India. I am a curious person who is always trying to wrap my head around new technologies. In my free time, I read novels and play with my dog!

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms