JavaScript Comments
JavaScript comments are notes written inside JavaScript code for developers and other readers. They explain what the code does, why a particular approach is used, or what a specific section is meant to accomplish.
Comments are ignored by the JavaScript engine during execution. This means they do not change the result of a program.
Comments are useful in small scripts as well as large applications. They can make code easier to understand, maintain, debug, and update.
JavaScript supports two main types of comments:
- Single-line comments
- Multi-line comments
What Are JavaScript Comments?
A JavaScript comment is text inside a JavaScript file that is not treated as executable code.
For example:
// This is a JavaScript comment
let name = "Dibya";
The JavaScript engine ignores the text after //.
Comments are mainly written for humans, not computers. They help explain the purpose and logic of code.
For example:
// Calculate the total price
let total = price + tax;
The comment does not perform the calculation. The following JavaScript statement does.
Why Are Comments Important in JavaScript?
Comments can make programming easier to understand, especially when code becomes large or complex.
They can be useful for several reasons.
1. Explain Code
A comment can explain what a particular piece of code does.
// Convert the temperature from Celsius to Fahrenheit
let fahrenheit = (celsius * 9 / 5) + 32;
A developer can understand the purpose of the calculation quickly.
2. Explain Why Code Exists
Sometimes the code itself is easy to understand, but the reason behind it is not.
// Keep this delay to prevent repeated API requests
setTimeout(loadData, 500);
This type of comment can be more valuable than simply describing the syntax.
3. Improve Maintainability
When someone returns to a project after several months, useful comments can help them understand important decisions.
4. Help Team Members
In a team project, comments can provide additional context to other developers.
5. Temporarily Disable Code
Comments can also be used to temporarily prevent a line of code from running.
let name = "Dibya";
// console.log(name);
The console.log() statement will not execute because it has been commented out.
However, commenting out large amounts of code is usually not a good long-term replacement for proper version control.
Single-Line Comments in JavaScript
A single-line comment begins with two forward slashes:
//
Everything after // on that line is treated as a comment.
Example:
// This is a single-line comment
let age = 25;
The comment can also appear after a JavaScript statement:
let age = 25; // Store the user's age
The code before the comment runs normally.
Examples of Single-Line Comments
// Store the user's name
let name = "Dibya";
// Store the user's age
let age = 25;
// Display the user's information
console.log(name, age);
These comments make the purpose of each line easier to understand.
Multi-Line Comments in JavaScript
JavaScript also supports comments that span multiple lines.
A multi-line comment starts with:
/*
and ends with:
*/
Example:
/*
This is a multi-line comment.
It can contain several lines
of explanatory text.
*/
The entire section is ignored by the JavaScript engine.
Multi-Line Comment Example
/*
Calculate the final price.
The final price includes
the product price and tax.
*/
let finalPrice = price + tax;
Multi-line comments are useful when a longer explanation is necessary.
Difference Between Single-Line and Multi-Line Comments
| Feature | Single-Line Comment | Multi-Line Comment |
|---|---|---|
| Syntax | // | /* ... */ |
| Lines | Usually one line | Multiple lines |
| Best for | Short explanations | Longer explanations |
| Example | // Calculate total | /* Calculate the total price */ |
Both types are ignored during JavaScript execution.
Comments After Code
A comment does not always have to appear on a separate line.
You can place a comment after a statement:
let score = 90; // Student's score
This is called an inline comment.
Inline comments are useful when the explanation is short.
For example:
let maxUsers = 100; // Maximum allowed users
However, avoid making inline comments so long that they make the code difficult to read.
Comments Before Code
A comment can be placed before the code it describes.
// Calculate the user's age
let age = currentYear - birthYear;
This is often easier to read than placing a long explanation at the end of a line.
Commenting Out JavaScript Code
You can temporarily disable JavaScript code by converting it into a comment.
For a single line:
// console.log("Hello World");
For multiple lines:
/*
console.log("Hello");
console.log("Welcome");
console.log("Goodbye");
*/
The commented code will not execute.
This can be useful while testing or debugging.
However, code that is permanently unused should generally be removed rather than left commented out. Version-control systems such as Git can preserve older versions of the code.
JavaScript Comments and Execution
Comments do not produce JavaScript output.
For example:
// This line is ignored
console.log("Hello");
The output is:
Hello
The comment has no effect on the output.
Similarly:
/*
This entire section is ignored.
*/
let message = "Hello";
console.log(message);
The output is:
Hello
Comments Are Not Strings
A comment and a string are completely different things.
A string is data that JavaScript can use:
let message = "Hello World";
A comment is ignored:
// Hello World
The text Hello World in the first example is stored in the message variable. The text in the second example is not stored or executed.
Comments Inside Functions
Comments can be used inside functions to explain important steps.
function calculateTotal(price, tax) {
// Add tax to the original price
return price + tax;
}
This can make the function easier to understand.
However, if the function is already very simple, a comment may not be necessary.
For example:
// Add two numbers
function add(a, b) {
return a + b;
}
The function is already very clear. The comment adds little value.
A better approach is often to use meaningful function and variable names.
Comments Inside Conditional Statements
Comments can explain why a condition is necessary.
if (user.isLoggedIn) {
// Show private content only to authenticated users
showDashboard();
}
This can be particularly helpful when the condition involves complicated business rules.
Comments Inside Loops
Comments can explain the purpose of a loop.
// Process each product in the shopping cart
for (let product of products) {
calculatePrice(product);
}
Avoid commenting every obvious line inside a loop.
Comments in JavaScript Objects
Comments can also be used around object properties.
const user = {
// Basic account information
name: "Dibya",
age: 25,
// Account status
active: true
};
This can help organize large objects.
Comments in Arrays
Comments can also explain groups of values in arrays.
const fruits = [
"Apple",
"Banana",
"Mango"
];
If the purpose is not obvious, you could write:
// Fruits available in the store
const fruits = [
"Apple",
"Banana",
"Mango"
];
Comments in JavaScript Classes
Comments can explain the purpose of a class or an important method.
class User {
// Create a new user with a name
constructor(name) {
this.name = name;
}
// Display the user's name
showName() {
console.log(this.name);
}
}
For larger classes, comments can help readers understand the responsibilities of different methods.
JavaScript Documentation Comments
JavaScript developers sometimes use special comments to document functions, parameters, return values, and other parts of code.
A common format is JSDoc.
Example:
/**
* Adds two numbers.
* @param {number} a The first number.
* @param {number} b The second number.
* @returns {number} The sum of the two numbers.
*/
function add(a, b) {
return a + b;
}
JSDoc uses a multi-line comment beginning with /**.
It is more structured than an ordinary comment.
What Is JSDoc?
JSDoc is a documentation syntax commonly used with JavaScript projects.
It allows developers to describe:
- Functions
- Parameters
- Return values
- Classes
- Variables
- Types
- Properties
- Exceptions
- Examples
A simple example is:
/**
* Greets a user.
* @param {string} name - The user's name.
* @returns {string} A greeting message.
*/
function greet(name) {
return `Hello, ${name}!`;
}
Tools and development environments can use JSDoc information to provide better documentation and developer assistance.
JavaScript Comments in HTML
When JavaScript is placed inside an HTML document using a <script> element, JavaScript comments can be written normally.
<script>
// Display a message
console.log("Hello World");
</script>
You should use JavaScript comment syntax for JavaScript code.
Modern HTML does not require old HTML-comment techniques around JavaScript.
JavaScript Comments in External Files
Comments can also be used in external .js files.
For example:
// main.js
const username = "Dibya";
console.log(username);
The browser ignores the comment when executing the JavaScript file.
Comments in Modules
JavaScript modules support the same comment syntax.
// Export the utility function
export function add(a, b) {
return a + b;
}
Comments do not affect whether a module is imported or exported.
Comments and Whitespace
Comments are generally treated as non-executable text and can appear where JavaScript grammar allows them.
For example:
let x = 10; // Value of x
let y = 20; // Value of y
They can make source code easier to scan without changing the program’s intended behavior.
Comments and Automatic Semicolon Insertion
Comments do not replace JavaScript syntax.
For example:
let x = 10 // This is a comment
let y = 20
JavaScript’s automatic semicolon insertion rules may allow this code to work, but comments themselves do not act as semicolons.
It is important to understand JavaScript syntax separately from comments.
Nested Comments in JavaScript
JavaScript does not support ordinary nested block comments.
For example, this is problematic:
/*
Outer comment
/*
Inner comment
*/
*/
The first */ ends the block comment. The remaining */ is then not valid in that position.
If you need to comment out a block that already contains block comments, be careful with nested /* ... */ structures.
Comments and Regular Expressions
JavaScript comments use // and /* ... */, but / is also used for regular expressions and division.
For example:
let result = 10 / 2;
Here / means division.
But:
let pattern = /hello/;
Here /hello/ is a regular expression literal.
A comment begins with // when JavaScript parses the characters as comment syntax.
Good JavaScript Comments
A good comment adds useful information that is not immediately obvious from the code.
For example:
// Use UTC because users can access the application from different time zones
const date = new Date();
This explains an important design decision.
Another useful example:
// Retry the request once because the service occasionally returns a temporary 503 error
The comment explains why the behavior exists.
Bad JavaScript Comments
A comment is not useful when it simply repeats obvious code.
For example:
// Create a variable called name
let name = "Dibya";
The code is already clear.
Another example:
// Add 1 to count
count++;
The comment provides little additional information.
Better comments explain context, reasoning, limitations, or important assumptions.
Explain Why, Not Just What
One of the best practices for writing comments is to explain why something is done when the reason is not obvious.
Instead of:
// Set timeout to 5000
setTimeout(loadData, 5000);
A more useful comment might be:
// Wait 5 seconds before retrying to avoid overwhelming the server
setTimeout(loadData, 5000);
The second comment gives meaningful context.
Keep Comments Up to Date
Incorrect comments can be worse than no comments.
For example:
// Allow users to upload up to 5 MB
const maxFileSize = 10 * 1024 * 1024;
The code allows 10 MB, but the comment says 5 MB.
This creates confusion.
Whenever code changes, related comments should also be reviewed.
Avoid Excessive Comments
Not every line needs a comment.
Too many comments can make code harder to read.
Poor example:
// Create variable
let name = "Dibya";
// Create another variable
let age = 25;
// Print name
console.log(name);
The code is already simple.
Better:
const name = "Dibya";
const age = 25;
console.log(name);
Use comments when they provide additional value.
Use Meaningful Variable Names
Good variable names can reduce the need for comments.
Instead of:
// Store the maximum number of login attempts
let x = 5;
Use:
const maxLoginAttempts = 5;
The name explains the purpose.
This is often better than relying on a comment.
Comments for Complex Algorithms
Comments are especially useful for complicated algorithms.
// Use binary search because the array is sorted.
// This reduces the search from linear time to logarithmic time.
function findValue(numbers, target) {
// ...
}
Such comments can help future developers understand the reasoning behind the implementation.
Comments for Important Warnings
Comments can warn developers about limitations or potential problems.
// Do not remove this check.
// The API may return null when the user has no profile.
if (profile) {
displayProfile(profile);
}
This type of comment can prevent accidental changes that introduce bugs.
TODO Comments
Developers often use TODO comments to mark unfinished work.
Example:
// TODO: Add pagination for large result sets
Other common forms include:
// FIXME: Handle network errors
// NOTE: This function assumes the input is already sorted
These are conventions rather than special JavaScript keywords.
JavaScript itself does not automatically give TODO or FIXME comments special meaning.
Some code editors and development tools can recognize them.
TODO, FIXME, and NOTE
These comment labels are commonly used for organization.
| Label | Common Meaning |
|---|---|
TODO | Something that should be completed later |
FIXME | Something known to need fixing |
NOTE | Important information |
WARNING | A potential problem or caution |
Example:
// TODO: Improve loading performance
// FIXME: Handle invalid input
// NOTE: This function returns data in UTC
// WARNING: This operation may take several seconds
These are conventions, not built-in JavaScript commands.
Comments and Debugging
Comments can be useful during debugging.
For example:
// Temporarily disable caching while testing the API
// enableCache();
However, comments should not become a permanent substitute for proper debugging and version control.
Developers can use browser developer tools, breakpoints, logging, and other debugging techniques to investigate problems.
Can Comments Affect Performance?
Comments are not executed as JavaScript instructions.
During normal development and production build processes, comments may remain in source files or may be removed by build and minification tools.
Removing comments can reduce source-file size, but well-configured production tooling typically handles this automatically when appropriate.
The main purpose of comments is therefore developer understanding, not runtime performance.
Comments in Minified JavaScript
Production JavaScript is often minified to reduce file size.
For example, readable code:
// Calculate the total
let total = price + tax;
console.log(total);
may be transformed into a compact form such as:
let total=price+tax;console.log(total);
Depending on the tool and configuration, comments may be removed during minification.
Some special comments may be preserved intentionally, such as license information.
License Comments
Open-source JavaScript projects sometimes include copyright or license comments.
For example:
/*!
* Example Library
* Copyright 2026 Example
* Licensed under the MIT License
*/
The ! is commonly recognized by some minification tools as a signal to preserve the comment.
The exact behavior depends on the build or minification tool being used.
Comments in JSON Are Different
A common mistake is assuming that JavaScript comments work in standard JSON.
Standard JSON does not support JavaScript-style comments.
This is invalid standard JSON:
{
// User information
"name": "Dibya"
}
Standard JSON should instead be:
{
"name": "Dibya"
}
Some JSON-like formats and tools support comments, but that is outside standard JSON.
Comments in JavaScript Configuration Files
Some JavaScript configuration files are actually JavaScript files, so normal JavaScript comments can be used.
For example:
// Configuration for the application
const config = {
port: 3000
};
However, if a configuration file uses strict JSON syntax, comments are not allowed.
Always check the format used by the specific tool.
Common Mistakes with JavaScript Comments
Mistake 1: Forgetting the Closing Block Comment
Incorrect:
/*
This comment never ends
let x = 10;
The comment continues until JavaScript finds a closing */.
Correct:
/*
This comment ends here
*/
let x = 10;
Mistake 2: Incorrectly Nesting Block Comments
Avoid nested block comments because JavaScript does not support them in the usual way.
Mistake 3: Writing Outdated Comments
If the code changes, update comments that describe the changed behavior.
Mistake 4: Commenting Every Line
Too many comments can create visual clutter.
Mistake 5: Using Comments Instead of Better Names
A clear variable name is often better than a comment explaining an unclear variable.
Mistake 6: Leaving Old Code Commented Out
Large blocks of dead code make files difficult to maintain. Version control is usually a better way to preserve previous implementations.
JavaScript Comment Examples
Single-Line Comment
// This is a single-line comment
Inline Comment
const age = 25; // User's age
Multi-Line Comment
/*
This is a multi-line comment.
It can contain multiple lines.
*/
Commented-Out Code
// console.log("This will not run");
JSDoc Comment
/**
* Returns the square of a number.
* @param {number} number
* @returns {number}
*/
function square(number) {
return number * number;
}
JavaScript Comments Best Practices
Follow these practices when writing comments:
- Write comments for clarity.
- Explain important decisions and reasons.
- Keep comments short when possible.
- Keep comments accurate and updated.
- Use meaningful variable and function names.
- Avoid explaining obvious code.
- Use JSDoc when structured documentation is useful.
- Use
TODOandFIXMEcarefully. - Avoid leaving large amounts of unused code commented out.
- Use comments to explain complex logic or unusual behavior.
- Keep comments professional and relevant.
- Follow the commenting conventions used by your project.
JavaScript Comments vs Documentation
Comments and documentation are related, but they are not exactly the same.
A comment might explain one part of an implementation:
// Retry once if the request fails temporarily
Documentation might explain how an entire function or API should be used.
For example:
/**
* Fetches the user's profile from the server.
* @param {string} userId - Unique user identifier.
* @returns {Promise<Object>} The user's profile.
*/
For larger projects, documentation should complement good comments rather than replace them.
Frequently Asked Questions About JavaScript Comments
What is a comment in JavaScript?
A comment is text written in JavaScript source code that is ignored by the JavaScript engine. It is mainly used to explain code to developers.
How do you write a comment in JavaScript?
Use // for a single-line comment:
// This is a comment
For a multi-line comment, use:
/*
This is a
multi-line comment
*/
How many types of comments are there in JavaScript?
JavaScript has two primary comment forms: single-line comments using // and multi-line comments using /* ... */.
Does JavaScript execute comments?
No. JavaScript comments are not executed as program instructions.
Can comments be placed after code?
Yes.
let x = 10; // This is an inline comment
Can JavaScript comments span multiple lines?
Yes. Use /* to start and */ to end a multi-line comment.
Can comments be used to disable code?
Yes. A line or block of code can be commented out temporarily.
Does JavaScript support nested comments?
JavaScript does not support normal nested block comments.
What is a JSDoc comment?
A JSDoc comment is a structured documentation comment that usually begins with /** and can describe functions, parameters, return values, classes, and other code elements.
Do comments affect JavaScript output?
Normally, comments do not affect the program’s runtime output because they are ignored as executable instructions.
Are comments necessary in every JavaScript program?
No. Simple and self-explanatory code may need very few comments. Comments are most useful when they explain non-obvious logic, important decisions, assumptions, or limitations.
Can comments improve code readability?
Yes. Well-written comments can improve readability by providing context that cannot be easily understood from the code alone.
Can comments make code worse?
Yes. Excessive, misleading, outdated, or unnecessary comments can make code harder to understand.
Are TODO comments part of JavaScript?
No. TODO, FIXME, and NOTE are common developer conventions. They are not JavaScript keywords.
Final Thoughts
JavaScript comments are a simple but important part of writing maintainable code. They allow developers to add explanations, document important decisions, describe complex logic, and leave useful notes for future development.
The two fundamental forms are easy to remember:
// Single-line comment
and:
/*
Multi-line comment
*/
The best comments do more than repeat what the code already says. They provide useful context, especially when explaining why something works in a particular way.
Good JavaScript code should ideally be understandable through clear names, simple structure, and logical organization. Comments should then provide additional information where it genuinely helps. When used thoughtfully, comments make JavaScript projects easier to read, debug, maintain, and improve.