Table of Contents
Javascript comments are mainly used to explain JavaScript code, document code, and block codes to prevent execution by the compiler. Here in this article we are going to discuss about “Comment in Javascript and how to write comment in javascript”.
As a javascript developer you must realize that, proper Javascript comments help programmers to increase readability, test alternative code performance, note down code block functionalities, and also help to control different code versions within the same file.
Moreover, in recent days – shorthand coding has gained popularity, which increases code complexity at a time. In this context, understanding codes written by others is very critical. Am I right? Not only you but also every developer faces this issue at least once. To overcome this issue, it’s obvious to write proper code comments from easy to complex code blocks to make them understandable to other developers or newcomers.
Single Line Comment in Javascript
Single line comments are very useful to add a quick comment or explanation over a line of code. Now the question is – what do you place in front of a line of code to make it a comment in javascript? Well the answer is – In JavaScript, single-line comments start with //.
Example #1: Single Line Comment in Javascript
// Change article title:
document.getElementById("articleTitle").innerHTML = "How to Comment in Javascript";
// Change article author:
document.getElementById("articleAuthor").innerHTML = "Shawpnendu Bikash Maloroy";
Example #2: Write Proper Comment for Documentation
// Declaring Global Variable Topic Title
let sTopic = 'Coders Tech Zone';
console.log(sTopic)
// Add title into the Global Post Array -- See appendix #2
postArray.push(sTopic)
console.log(postArray)
You can also use a single line comment at the end of each line to explain the code purpose:
let var1 = 7; // Declare First Variable
let var2 = var1 + 3; // Declare the Calculated Variable
Multiline Comment in Javascript
Most of the times a single line comment cannot explain or document a complex code block. In these cases, adding two forward slashes at the start of each line is a very tedious job for developers. At this particular point, a JavaScript developer bound to choose multiple lines for comments. Block comments are another name for a multi-line JavaScript comment.
Multi-line comments start with /* and end with */. Any text between /* and */ is ignored by JavaScript compiler.
Example: how to make a multi-line comment in javascript
/* It's a multi line comment.
You can write a complete details of your code here
Details #1: ................
Details #2: ................
Details #3: ................
.
.
.
*/
console.log("Multiline comment ........");
JavaScript Comments to Prevent Execution
During testing your own code, adding two forward slashes (//) in front of code lines or placing code or notes in between /* and */ will convert the code/code block respectively to a comment, rather than an executable line.
So, the ultimate take way is JavaScript comment can purposefully use to locate problems of code or while testing new features.
Example #1: Uses // to prevent execution of one of the code lines
//document.getElementById("articleTitle").innerHTML = "How to Comment in Javascript";
document.getElementById("articleTitle").innerHTML = "5 Best Ways to Write Comment in Javascript";
Example #2: Uses /* and */ to prevent execution of multiple lines
/*
document.getElementById("articleTitle").innerHTML = "How to Comment in Javascript";
document.getElementById("articleTitle").innerHTML = "5 Best Ways to Write Comment in Javascript";
*/
document.getElementById("articleTitle").innerHTML = "How to Comment Your JavaScript Code!";
Shortcut key for Comment in Javascript
Most of the code editors have two shortcut keys for line and block comments. And as a developer you have to be familiar with all shortcut keys.
- Line comments shortcut key is ctrl + / on Windows/Linux or cmnd + / on OSX.
- Multi line or block comments shortcut key is Ctrl + Shift + / for PC. And Command + Opt + / for Mac.
The biggest difference with block comments is their high sensitivity to selection. The block comment shortcut usually inserts an empty block comment at the cursor position if nothing is selected. It will only wrap the selection if you have one. Like:
Uncomment a line / lines
- Select the required line(s).
- Press Ctrl + /
Purpose of ‘@’ Symbol in JavaScript Multiline Comments
/**
* Check if a value in existing list
*
* @param {*} val
* @returns {Boolean}
*/
In most javascript code documentation we found @ symbol to highlight some line/code everywhere. Don’t worry about it. It’s just a JSDoc syntax.
Such as @throws to identify the expected exceptions that certain code may throw, or @copyright to define a license. Certain syntax is unique to functions or methods, while others are particular to objects or even entire files.
Look at the below code block:
/**
* @param {number} val
* @return {boolean}
*/
function foo(val) {}
Here @param means It’s a parameter. The value inside {} denotes the data type of the parameter – * means “any”, but you can use specific DT (data type) like string or number such as @param {string} or @param {number}.
“val” is the name of the function parameter.
Optionally you can add a description for the “val” function parameter. Like @param {*} val – used for vat calculation. Here “used for vat calculation” is the function description.
The @return denotes the return type of the function.
Inside {} is the return data type again. In this case, a Boolean.
Optionally you can add a description for the “val” function parameter. Like @returns {Boolean} true if correct, false if incorrect.
Why Comments are Important in JavaScript
- Code Documentation: Code documentation is very important for developers. It’s not only used to understand the code but also an asset for future code revision. If you can write proper comments, then you can automatically generate documentation. Now a days, it’s very easy without giving any further effort. This can be useful for large projects with complex APIs.
- Clarity and Readability: Let’s consider you are writing code for a very unknown system like a faucet system. In those cases, variable names (actually different faucet names) can be complicated for your other team members. You can make the names of variables or functions more readable or understandable to others by writing a proper explanation using comments.
- Debugging and Troubleshooting: Comments are also used to temporarily disable or “comment out” sections of code for debugging purposes. In most cases, we need to keep multiple versions of the same code in the same code file. How? Only commenting can help us in this regard. So that we can revert back in case of any mesh.
- Team Collaboration: In a collaborative environment, comments can ease communication between team members to discuss approaches, explain decisions, or suggest improvements. Imagine Git-related comments. How important are those?
Finally, we would like to say that comments play a vital role in maintaining clean, understandable, and maintainable code. Not only for JavaScript but also for other programming languages.
Best Practices for Writing Code Comments in JavaScript
Code-commenting is an art. Almost 69.7% of developers feel the reality of code commenting, as per the StackOverflow survey. Coders are different people. That’s why they write their comments differently. But it’s required to maintain some rules so that the corresponding code is more understandable to others and future-upgrade-friendly. Here are the most commonly practiced rules:
- Comments must be concise and meaningful: To be clear, commenting is very important. Unnecessary details are not acceptable at all. Moreover, comments should not duplicate the code.
- Clear and descriptive: Comments must be clear and easy to read. So that others can understand the purpose of a block or line of code. An easy and understandable comment can save enormous time. You can also realize this issue even if you come back for your own code medication after a few months.
- Put Links to Outside Resources from Where You Copied: It’s a must practice to put all resource references in your code. So that others can easily read those documents whenever required.
- When explaining complicated or unique code, use comments: It’s always tough to understand the business logic of a set of code. Only the code author can explain it in a very easy way. So don’t be lazy while writing comments. Explain the logic behind business scenarios first, then start your coding.
- Add comments when fixing bugs: Not only should you write your comment while writing fresh code, but it’s also advised to modify or add additional comments according to a new change or bug fix.
- Use comments for incomplete implementations: Considering future changes, solution architects may introduce or force developers to write additional methods or functions. Keep in mind that, as a developer, it’s your duty to write the proper reason behind the new unused method introduction.
Common Mistakes to Avoid
- Don’t make your comment too long or too complex. Then, it will take more time to understand your comment than the code.
- Update your comments from time to time, particularly after corrections or adjustments are made. If not, your remarks will become irrelevant very quickly.
- Provide enough context or explanation for every complex logic in the comments. Otherwise, the code will create more complexity for other developers.
- Don’t make any confusion while writing comments. Be concise and to the point.
- Don’t make any personal or unnecessary comments. Always keep in mind that you are not only writing comments for yourself but also for other developers.
- Emphasize the readability and maintainability of the code while writing comments. Otherwise, you or your team will fall into longer development cycles and higher expenses.
Conclusion
So, after this long discussion on “Comment in Javascript: How to Comment in Javascript” you must know how to comment and why commenting is necessary for a JavaScript developer. Finally, we would like to say again that commenting is not wasting your time; rather, it will improve code collaboration, code management, and code debugging.
By following our best practices and guidelines, use various comment types in your code right now. So that you can create a codebase that is easily understandable, manageable, and ready to accommodate future changes.
Frequently Asked Questions
Can you comment out JavaScript?
Yes. There are 2 Types of Comments in JavaScript. Single-line comments and multi-line comments. Both are discussed above. Use accordingly.
What is the Best Comment in JavaScript?
Some of the best practices are:
1. Don’t make your comment too long or too complex
2. Update your comments time to time
3. Provide enough context or explanation on every complex logic
4. Don’t make any confusion while writing comments
5. Don’t write any personal or unnecessary comments
6. Emphasize on readability and maintainability of the code
To know more details read our “Common Mistakes to Avoid” section mentioned above.
How to Comment a Class in JavaScript?
There is no specific difference in writing comments. Just use single line syntax (//) or multi line syntax (/* */) whatever required.
How do you comment mark in JavaScript?
For single line commenting use “//” before starting the comment line. And use “/* */” for multiline comments. Don’t afraid compiler will ignore those comments.
How do you comment multiple lines in JavaScript?
Multi-line comments start with /* and end with */. Any text between /* and */ is ignored by JavaScript compiler.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply