This content originally appeared on Bits and Pieces - Medium and was authored by Nipuni Arunodi
How to Use Comments Efficiently in JavaScript
Using comments helps to understand code and its purpose. However, many developers are not aware of using comments correctly, and sometimes they make things over complicate.
So, in this article, I will discuss when you should use comments and the best practices you need to follow.
There are 2 Comment Syntaxes in JavaScript
Each programming language has its own set of syntax when it comes to comments. In JavaScript, there are two syntaxes dedicated to comments. So, before getting into details, let’s quickly go through these two syntaxes.
1. Single-line Comments
In JavaScript, single-line comments begin with //. It will ignore all the things immediately after // syntax until the end of that line.
// Single line
This is also known as inline commenting when we use // syntax alongside codes lines. It is the most precise form of comment because it only relates to the specific code line it is written on.
let p= 3.14; // The value of Pi (π)
let a = 2 * p * 10 // Circumference of circle with radius 10
2. Multi-line Comments
Multi-line or block comments serve the same purpose and as the name suggest, it expands into multiple lines.
Usually, most developers use /* and */ syntax to write multi-line block comments. But the standard way to use block comments in JavaScript is to;
- Start with /** in a blank line.
- End with */ at the end line.
- Use * at the beginning of each line between start and the end.
/* Normal
Multi-line
Comment */
/**
* Standard
* Multi-line
* Comment
*/
When Should You Use Comments in JavaScript?
As I mentioned, most of the time, developers use comments to explain code. But there is much more beyond that.
1. Prefacing
Prefacing or explaining the code is one of the main goals of using comments. It’s not only for other developers; you might also need to refer to it later on.
You can either use inline comments or use a block comment with a brief explanation of its use.
let result = getVisibleComponents(); // Retrieve UI components in Viewport
2. For Debugging
Since the JavaScript engine does not interpret commented-out codes, we can use comments for debugging purposes.
For example, if there is an error in your code, you can comment out code lines and re-run the code to see which line I am causing the error.
3. Tagging
Using JSDocs Tags is another good practice development teams can follow to express their ideas on code to team members.
Tags add a semantical structure to your comments. That, in turn, allows development tools to use this data for smart analysis.
/**
* @example
* // returns 6
* multiplication(2, 3);
* @example
* // returns -6
* @param {number} a - a number to multiply
* @param {number} b - a number to multiply
* multiplication(-2, 3);
*/
function multiplication(a, b) {
return a * b;
};
Likewise, you can use many tagging options, and these tags give a clear indication for other developers who visit your work.
Bit, for example, uses JSDocs tags to generate a properties table for components:
4. Store Metadata
Storing metadata of a file is another common use of comments. For example, we can include information author, version, repo links within metadata, and they become handy in open-source applications.
/**
* @author Nipuni Arunodi
* @version 0.0.1
* ...
*/
Note: These usages are not defined or fixed. Developers can have their own practices, and I have presented some of the most used scenarios.
Best Practices to Follow When Using Comments
There are no pre-defined rules to use comments. But as an individual or a team, it is essential to agree upon some best practices around comments for consistency.
1. Code tells `how` and comments tells `why`
Comments should be insightful for the person who reads them, and we should always avoid writing how the code works in comments. Here, the code should be able to self-explain how it works, keeping comments to address why it’s there in the first place.
// Do
let p = 3.14; // Rounded value of Pi
let c = 2 * p * 10; // Calculate the circumference of a circle with radius 10
// Don't
let p = 3.14; // Initiate the value of the variable p
let c = 2 * p * 10 // Multiply the value p into 20
2. Only use the necessary level of details
Using comments is good. However, you shouldn’t overdo it by describing the code beyond what’s required. The challenge here is that you also need to maintain comments and modify them. Besides, it could negatively affect the readability of the code.
// Do
/**
* Retrieve a list users from the database
*/
async function getUsers() {
// ...
}
// Don't
/**
* Retrieve a list of user objects asynchronously by invoking a database query
*/
async function getUsers() {
// ...
}
3. Avoid Abbreviations
We shouldn’t use abbreviations like aka, viz because not everyone understands them. Although they make your sentences short, it defies the purpose of conveying a clear message to the reader.
// Do
/**
* regEx, in other words Regular Expressions
*/
// Don't
/**
* regEx, viz. Regular Expressions
4. Use comments before code
The main purpose of writing comments is to let readers know what they can expect from our code. Thus, they will read the comments and understand what is going on before going through the code.
So, it is always good to use comments above the code you explain, and it will save a lot of time for the reader.
/**
* Fetches articles of a writer based on writerId
* @param {string} writerId - The Id of the writer.
*/
function getArticles(writerId) {
// ...
}
5. Pay extra attention to numeric values
Dealing with numeric values can always be tricky since there are specific ranges and units used. Here, we can use comments to explain the units used and their ranges. Also, If there are any restrictions on input data, we can mention them in our comments.
6. Take editor Support
All the modern-day code editors provide their support towards using comments. So, we need to get the maximum out of it.
For example, you can use ctrl + / to comment out a single code line or a code block in any editor. Also, they auto-completes block code syntax when you type opening syntax (/**).
Besides, there are plugins like Better Comments available for VSCode. These extensions help to create more readable comments like below:
Conclusion
In this article, I discussed several use cases of comments in JavaScript and the best practices we need to follow.
As developers, we should always adhere to those best practices since it will increase readability and make it easier for you and your team to understand your code.
I hope those suggestions will help you improve the readability of your code and if you have any suggestions, please share them with others in the comments section.
Thank you for Reading!!!
Build better Component Libs and Design Systems
Share components across teams and projects to speed up development and make sure your users experience a consistent design at every touchpoint.
OSS Tools like Bit offer a great dev experience for building, sharing, and adopting components across teams and applications. Create a component hub for free give it a try →
Learn More
- React TypeScript: Basics and Best Practices
- 6 Tips and Best Practices for a Scalable React Project
- Best Practices in Using IFrames with React
Best Practices For Using Comments In JavaScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Nipuni Arunodi
Nipuni Arunodi | Sciencx (2021-09-14T16:59:47+00:00) Best Practices For Using Comments In JavaScript. Retrieved from https://www.scien.cx/2021/09/14/best-practices-for-using-comments-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.