Comments are code statements that are entirely ignored by JavaScript when it executes your program. They are meant solely for human consumption, whether it be you, your team members, or any person reading the code in the future. Even if you have no previous experience coding with JavaScript whatsoever, comments are among the simplest concepts to grasp since they do not influence the behavior of your program in any way. In this tutorial, we will take an in-depth look at all types of comments, their importance, proper usage, and mistakes to avoid along the way, using code examples.
Table of Contents
What Are JavaScript Comments?
Before exploring the various types, it will be useful to get a clearer idea of what a comment is and how JavaScript processes it as your code runs.
- Definition of Comment: A comment is any text in your source code that JavaScript ignores completely when executing your code. It has absolutely no impact whatsoever on your program output.
- Purpose in Code: A comment describes the reasoning behind something in the code, acts as a reminder, or explains the purpose of a particular block of code.
- Never Executed: The JavaScript interpreter does not run any comments; no matter how lengthy or complex they may be, it skips right over them.
- Human Notes Only: You can treat comments in your code just like Post-It notes in your office; you make notes to yourself about your code.
- Comments Not Visible: Comments are never visible anywhere except in your source code file.
// This is a comment. It will not run or show up anywhere on the webpage.
console.log("Hello, World!"); // This line actually runs
Types of JavaScript Comments
In JavaScript, there are two types of comments. The first thing one needs to know is when to use them.
- Single Line Comments: They use two forward slashes (//). Anything that comes after //on that line becomes a comment.
- Multi-line Comments: It uses /* to start and */ to terminate. Anything between these symbols becomes a comment, even if it extends to several lines.
- Usage of Inline Comment: A single-line comment added at the end of a line of code.
- Usage of Block Comment: A multi-line comment added to comment out a bigger block of code.
- Restrictions on Nesting: Multi-line comments cannot be nested within each other.
// Single-line comment example let age = 25; // Inline comment explaining this variable /* Multi-line comment example. This can span as many lines as needed. Useful for longer explanations. */ let name = "Alex"; /* Correct: */ let score = 10; /* comment at end of line */ // Incorrect nesting (this causes an error): /* Outer comment /* Inner comment */ still outer */
Why Comments Matter for Beginners
Most programmers overlook the importance of commenting their programs by thinking that it is an additional task. However, it saves you a lot of time and trouble in the future.
- Code readability: Comments allow the person reviewing your code, whether it is yourself at a later point in time or anyone else, to grasp the idea behind the particular block of code.
- Facilitating teamwork: When working on a project along with other people, comments provide the intention behind a certain decision and help to avoid guessing.
- Making debugging easier: You can highlight possible bugs through comments or use them to explain a complicated way of fixing some problems.
- Explaining complex logic: Sometimes a certain calculation, workaround, or business rule needs to be explained in order to understand what the programmer was trying to achieve.
// Calculate the discounted price after applying a 20% seasonal discount let discountedPrice = originalPrice * 0.8;
How to Write Single-Line Comments?
Single-line comments are the most widely used type due to their fast typing and ease of identification.
- Basic Syntax Rule: Begin the comment with double slashes: //; the rest of the line will be considered a comment.
- Comment Placed Above Code: Place your comment on a new line above the line of code it refers to, which is helpful for long comments.
- Comment Placed Besides Code: Put your comment after a code line for brief notes related to that particular code line.
- Commenting Out Code: Disable the code line temporarily with // placed in front of it, while the line remains in the code.
- Short Comment: Do not use long comments, since the single-line comment cannot be automatically wrapped.
// Store the user's full name let fullName = "Jordan Lee"; let total = 100; // total price in dollars // console.log(total); // this line is disabled for testing
How to Write Multi-Line Comments?
Multi-Line comments are used if more than one line is needed for describing something.
- Open and Close Tags: Start with /* and end with */; everything in between is considered to be a comment, regardless of the number of lines.
- Describing a Function: Use a block comment before a function to explain its purpose, input, and output.
- Commenting out Multiple Lines: Place multiple lines of code within /* */, thus disabling them completely during debugging.
- Proper Formatting: It is common practice to put a * at the beginning of each line within the block (not required, though).
- Common Mistakes to Avoid: Make sure there is a corresponding */ after every /*; otherwise, all the following code will be commented out as well.
/*
* This function adds tax to a given price.
* It takes the base price and tax rate as inputs
* and returns the final price.
*/
function addTax(price, rate) {
return price + price * rate;
}
/*
let unusedVariable = 5;
console.log(unusedVariable);
*/
Best Practices for Writing Comments
But knowing how to write syntax is not all; learning how to make valuable comments deserves much attention as well.
- Why?: Comment on why the code exists or why some decisions were made, but not how the code will speak for itself.
- Keep Comments Current: Never forget to update/remove the comments whenever you update/delete the code.
- Don’t Repeat The Obvious: Try not to put obvious comments, such as explaining "Adds One" under count = count + 1.
- Consistency Is The Key: Decide on a comment style (joking/humor, serious, etc.) that works best for your whole project.
- Clear Language: Avoid complex sentences and jargon; write in a way that is comprehensible by everyone on the team.
// Bad: states the obvious // increase count by 1 count = count + 1; // Good: explains the reasoning // Increment count to track how many retries the user has attempted count = count + 1;
Common Mistakes to Avoid
Experienced coders also fall into these mistakes; hence, it is better to be aware of them before beginning.
- Too Much Commenting of Code: Commenting every single line of the code messes up the file and makes it difficult to notice the significant comments.
- Out-of-date Comments: An out-of-date comment is even more dangerous than not having any comment because it misleads others reading the code.
- Sparse Comments on Code: When there are no comments whatsoever on the logic of code, it becomes impossible for other developers to understand what was intended.
- Avoiding Commented-Out Code: It is advisable to remove any large pieces of commented-out code from the file; otherwise, it would make the file messy.
- Syntax Error in Commenting: You may forget to close the multiline comment, resulting in commenting out the whole file.
// This is broken because the multi-line comment was never closed:
/* This explains the next function
function greet() {
console.log("Hi!");
}
// Everything below this point is now accidentally commented out too
Documentation Comments with JSDoc
- JSDoc Definition: Multi-line comments written in a particular format that programs can read to automatically create documentation.
- Describing Function Arguments: The @param tag is used in a JSDoc comment to describe all the arguments a function expects.
- Describing Return Types: Use the @returns tag to describe what a function returns when it completes its execution.
- Providing Hints to Code Editors: Code editors read JSDoc comments to provide hints to the user while coding.
- Creating Documentation Files: Programs such as the JSDoc program create documentation files from the JSDoc comments automatically.
/**
* Calculates the area of a rectangle.
* @param {number} width - The width of the rectangle.
* @param {number} height - The height of the rectangle.
* @returns {number} The calculated area.
*/
function getArea(width, height) {
return width * height;
}
Conclusion
Commenting may appear to be insignificant at first glance, but in fact, it takes great importance in developing well-understood and maintainable code. For starters, try forming a habit of using one-liners for simple reminders and multi-liners for extensive descriptions, while being careful to explain the reasons for your code rather than its purpose only. Do not comment unnecessarily or include irrelevant information, and as you move forward, pay attention to such commenting techniques as JSDoc. Eventually, with proper training, writing meaningful comments will become your routine task – which you will be grateful for yourself in the future.
Frequently Asked Questions
1. Do comments slow down my JavaScript code?
No. Comments are removed or ignored before your code actually runs, so they have no effect on performance, no matter how many you write.
2. Can I use HTML-style comments (<!-- -->) in JavaScript?
No, that syntax is specific to HTML. JavaScript only recognizes // for single-line comments and /* */ for multi-line comments.
3. Is it bad practice to comment out code instead of deleting it?
Occasionally commenting out code for quick testing is fine, but leaving it in your final project is discouraged, use version control (like Git) instead to track old code safely.
4. What's the difference between a regular comment and a JSDoc comment?
A regular comment is free-form text for humans, while a JSDoc comment follows a specific structure (starting with /**) that tools can parse to auto-generate documentation.
5. Should every function in my code have a comment?
Not necessarily every function, but any function with non-obvious logic, tricky calculations, or an unclear purpose should have a short comment explaining its intent.
0 Comments