javascript

Comment Best Practices

Master JavaScript comment best practices. Learn to use single-line, multi-line, and JSDoc comments effectively for cleaner, more understandable, and maintainable code in your web projects.

10 min read 8 sections Tutorial
Share

Comments are like notes you write in your code. They help you and other programmers understand what your code does and why it works a certain way. Learning to write good comments makes your code much easier to read and maintain.

Comment Best Practices

Comment Best Practices

When you write code, you are telling the computer what to do. But sometimes, you also need to tell humans what your code does. That's where comments come in.

Comments are special lines of text that the computer ignores. They are only there for people to read. Good comments explain tricky parts of your code or why you made certain choices. This is very important when you work with others or look at your own code much later.

What is a Code Comment?

A code comment is a piece of text inside your program that is ignored by the compiler or interpreter. Its purpose is to explain the code to human readers, improving readability and understanding.

Explain 'Why'

Comments should explain the reasoning or purpose behind complex code, not just what the code literally does.

Keep Them Updated

Outdated comments can be worse than no comments. Always update comments when you change the code.

Avoid Obvious

Don't comment on code that is already clear. Good code should largely explain itself.

Use JSDoc

For functions and classes, use JSDoc to document parameters, return values, and overall purpose.

Types of JavaScript Comments

Getting Started

Types of JavaScript Comments

JavaScript has two main ways to write comments. These are single-line comments and multi-line comments. Each type is useful for different situations.

Knowing when to use each type helps keep your code neat and easy to follow. The computer treats both types the same way: it just skips over them.

javascript
1// This is a single-line comment.
2// It starts with two forward slashes and goes until the end of the line.
3let score = 100; // You can also put a single-line comment at the end of a line of code.
4
5/*
6This is a multi-line comment.
7It starts with /* and ends with */
8It can cover many lines of text.
9It's great for longer explanations.
10*/
11let playerName = "Alice";
12
13console.log(score); // Display the score
14console.log(playerName); // Display the player's name

Don't Comment Out Old Code

It's a common mistake to 'comment out' old code you don't need anymore. This clutters your file. Instead, delete the old code. Version control systems like Git keep a history of your changes, so you can always get it back if you need it.

Why Comments Are So Important

Why Comments Are So Important

Comments are not just for explaining what your code does. The best comments explain why your code does something. They describe decisions, assumptions, or complex logic that isn't immediately clear from the code itself.

Imagine you wrote some code a year ago. Without comments, you might forget why you made certain choices. Good comments act like a memory aid for you and a guide for others.

javascript
1function calculateDiscountedPrice(originalPrice, customerType) {
2 let discountPercentage = 0;
3
4 // Rule: Gold customers get a higher discount during weekdays.
5 // This complex logic prevents applying the highest discount on weekends.
6 if (customerType === 'gold' && new Date().getDay() >= 1 && new Date().getDay() <= 5) {
7 discountPercentage = 0.15; // 15% for Gold customers on weekdays
8 } else if (customerType === 'silver') {
9 discountPercentage = 0.10; // 10% for Silver customers anytime
10 } else {
11 discountPercentage = 0.05; // 5% for all other customers
12 }
13
14 const finalPrice = originalPrice * (1 - discountPercentage);
15 return finalPrice;
16}
17
18const price1 = calculateDiscountedPrice(200, 'gold');
19console.log('Gold customer price:', price1); // Example output: Gold customer price: 170 (if weekday)
20
21const price2 = calculateDiscountedPrice(150, 'silver');
22console.log('Silver customer price:', price2); // Example output: Silver customer price: 135
✗ BadBad — Explains Obvious 'What'
// Declare a variable named 'x'
let x = 10;
// Add 5 to x
x = x + 5;
// Print the value of x
console.log(x);
✓ GoodGood — Explains Non-Obvious 'Why'
// This value is hardcoded because it comes from a legacy system API.
// Do not change without verifying with the backend team.
const LEGACY_API_KEY = "abcd-1234-efgh";
function processData(data) {
// Using a specific sorting algorithm here because data volume is always small (under 100 items).
// For larger datasets, a more efficient algorithm would be needed.
data.sort((a, b) => a.id - b.id);
return data;
}

When to Comment and When Not To

When to Comment and When Not To

The best code is self-documenting. This means the code itself is so clear that it barely needs comments. You achieve this with good variable names, small functions, and simple logic.

However, some things are still hard to understand just by looking at the code. This is where comments are valuable. Always ask yourself: "Is this comment explaining something the code cannot explain?"

Better: Comment for 'Why'
// This regular expression is complex because it needs to match
// both single-word and hyphenated-word tags, ensuring no spaces.
const TAG_REGEX = /^([a-z]+(?:-[a-z]+)*)$/;
function validateTag(tag) {
return TAG_REGEX.test(tag);
}
VS
Avoid: Comment for Obvious 'What'
// Declare a variable named 'age'
let age = 30;
// Check if age is greater than 18
if (age > 18) {
// Log a message to the console
console.log("Adult");
}

Rule of Thumb: Explain 'Why', Not 'What'

If your comment just repeats what the code does (e.g., // Add 1 to count), it's probably not needed. If it explains the reason behind a tricky piece of logic or a specific design choice, then it's a good comment.

Using JSDoc for Professional Documentation

Using JSDoc for Professional Documentation

For more complex projects, especially when writing functions or classes, you will want to use JSDoc. JSDoc is a special way of writing multi-line comments that tools can understand.

It helps you describe functions, their inputs (parameters), and what they return. This creates useful documentation that appears when other developers use your code, making it much easier for them.

1

Start a JSDoc block

A JSDoc comment starts with /** (two asterisks) instead of /* (one asterisk).

javascript
1/**
2 * This is a JSDoc comment block.
3 */
2

Describe the function's purpose

On the first line after /**, write a short sentence explaining what the function does.

javascript
1/**
2 * Calculates the area of a rectangle.
3 */
3

Document parameters

Use @param {type} name - Description to explain each input parameter. {type} describes the kind of data, like {number} or {string}.

javascript
1/**
2 * Calculates the area of a rectangle.
3 * @param {number} width - The width of the rectangle.
4 * @param {number} height - The height of the rectangle.
5 */
4

Document the return value

Use @returns {type} - Description to explain what the function gives back.

javascript
1/**
2 * Calculates the area of a rectangle.
3 * @param {number} width - The width of the rectangle.
4 * @param {number} height - The height of the rectangle.
5 * @returns {number} The calculated area of the rectangle.
6 */
7function getRectangleArea(width, height) {
8 return width * height;
9}

Outdated Comments Are Harmful

A comment that says one thing while the code does another is very dangerous. It can confuse developers and lead to bugs. Always update your comments immediately when you change the code they describe. If a comment is no longer true, remove it.

Comment Types Quick Reference

Comment Types Quick Reference

Comment TypeSyntaxBest Use CaseExample
Single-line`// ...`Short notes, explaining a single line or a small block of code, at the end of a line.`let x = 5; // Initial value`
Multi-line`/* ... */`Longer explanations, commenting out blocks of code temporarily, header comments for files.`/* This function... ...does X and Y */`
JSDoc`/** ... */`Documenting functions, classes, modules. Provides structured information for tools and IDEs.`/** @param {string} name - User name */`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which type of comment is best for explaining a single line of code or a quick note?

Quick Check

What is the main purpose of a good comment?

Quick Check

What is the problem with this comment: // Add 1 to the counter variable for the line counter = counter + 1;?

Quick Check

When should you use JSDoc comments (/** ... */)?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Comments — text in your code that the computer ignores, for human readers only.
  • 2Single-line comments — start with //, useful for quick notes on one line.
  • 3Multi-line comments — start with /* and end with */, good for longer explanations.
  • 4JSDoc comments — start with /** and end with */, used for structured documentation of functions and classes.
  • 5Explain 'Why' — focus on explaining the reasoning, decisions, or complex logic, not just what the code does.
  • 6Avoid obvious comments — if the code is clear, a comment repeating it is clutter.
  • 7Keep comments updated — outdated comments are worse than no comments; always change them when code changes.
  • 8Self-documenting code — write clear code with good names so fewer comments are needed.
  • 9Don't comment out old code — delete it; version control handles history.
  • 10No performance impact — comments do not slow down your JavaScript program.

Clean Code Principles

Learn how to write code that is inherently easy to read and understand, reducing the need for comments.

Version Control with Git

Understand how Git helps manage code changes and why it's better than commenting out old code.

Code Linting

Discover tools that automatically check your code for style and potential errors, improving quality.

Debugging Techniques

Learn how to find and fix errors in your code, an essential skill for any developer.

You've Mastered Comment Best Practices!

You now understand the different types of comments in JavaScript, when to use them, and crucially, how to write comments that truly add value to your code. Good commenting is a sign of a professional developer!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning