W3docs

JavaScript Comments

Learn how to write JavaScript comments — single-line (//), multi-line (/* */), and JSDoc doc-comments for documenting functions and code.

Introduction

This chapter covers everything you need to write good JavaScript comments: the two comment syntaxes (// line comments and /* */ block comments), JSDoc doc-comments for documenting functions, the difference between helpful and harmful comments, and how to comment out code while debugging. Comments are text that the JavaScript engine ignores entirely during execution — they exist purely for humans. They explain your code to anyone who reads it later, including your future self and your teammates. Because they're stripped from execution, comments have no runtime cost. (One related directive that is read by the engine is "use strict"; despite looking like a string at the top of a file, it changes how code runs — see the strict mode chapter.)

Why Commenting is Essential in JavaScript

Commenting might seem secondary, but it plays a pivotal role in coding. It helps in:

  • Code Documentation: For explaining complex logic or reasoning behind certain code segments.
  • Code Readability: Enhancing the understanding of the code's flow and functionality.
  • Debugging: Easily enabling or disabling parts of code during testing or debugging.
  • Team Collaboration: Assisting other developers in understanding your thought process.

Types of JavaScript Comments

JavaScript supports two main types of comments:

Single-line Comments

Single-line comments start with // and extend to the end of the current line. Everything after // on that line is ignored. They can sit on their own line or at the end of a line of code (an inline comment):

// This whole line is a comment
let a = 5, b = 10;

let sum = a + b; // inline comment: add the two values

Because a // comment only runs to the end of the line, the next line is back to normal code — you don't need to "close" it.

Multi-line Comments

Multi-line comments (also called block comments) start with /* and end with */. Everything in between is ignored, even across many lines. Use them for longer explanations:

/*
  Returns the sum of two numbers.
  Both arguments are expected to be numbers;
  passing strings will concatenate instead of add.
*/
function add(a, b) {
    return a + b;
}

You can also use the block syntax in the middle of a line, for example to label an argument: setTimeout(run, 1000 /* ms */).

Gotcha — block comments do not nest. A */ ends the comment at the first occurrence, so wrapping code that already contains /* ... */ in another block comment breaks. The inner */ closes the comment early and the rest becomes live code:

/*
  /* inner */
  alert('this still runs!');
*/

To comment out a region that contains block comments, use // on each line instead.

Good vs. Bad Comments: Explain Why, Not What

The single most useful rule: comment the why, not the what. The code already says what it does; a good comment captures the intent, the trade-off, or the surprising constraint that the code can't express on its own.

// Bad: just restates the code — adds noise, can go stale
let total = 0; // set total to 0

// Good: explains a non-obvious constraint
const RETRY_LIMIT = 3; // the payment API rejects bursts above 3 calls/sec

Prefer self-documenting code over comments where you can. A well-named variable or a small function often removes the need for a comment entirely:

// Needs a comment because the intent is hidden:
if (u.a && Date.now() - u.l < 86400000) { /* active in last 24h */ }

// No comment needed — the names say it:
const isActive = user.isVerified && wasSeenInLast24Hours(user);
if (isActive) {
  // ...
}

A few more guidelines:

  1. Keep them current. A comment that contradicts the code is worse than no comment — readers can't tell which one to trust.
  2. Be concise. Explain the reasoning, not every step.
  3. Don't comment out dead code permanently. Delete it; version control remembers it.

Commenting Out Code

During debugging you often want to disable a line or block without deleting it. Prefix a line with //, or wrap a region in /* */:

let value = compute();
// console.log('Debug:', value); // temporarily silenced

/*
expensiveLogging(value);
sendToAnalytics(value);
*/

This is great for isolating which part of the code causes a problem. Many editors toggle this with a keyboard shortcut. See the Console API chapter for cleaner alternatives to leftover console.log debugging.

TODO and FIXME Markers

A common convention is to tag unfinished work with TODO (something to do later) or FIXME (a known bug). Editors and linters can list these for you:

// TODO: optimize this loop for large data sets
// FIXME: breaks when input is an empty array

JSDoc: Documenting Functions

JSDoc is a standard for documenting functions using a special block comment that opens with /** (two asterisks). Tags such as @param and @returns describe the inputs and output. Tooling and editors read these to show inline hints and to generate HTML documentation.

/**
 * Adds two numbers together.
 * @param {number} a - The first addend.
 * @param {number} b - The second addend.
 * @returns {number} The sum of a and b.
 */
function add(a, b) {
    return a + b;
}

console.log(add(2, 3)); // 5

JSDoc pairs especially well with functions: documenting parameters and return types makes a function's contract clear without reading its body. Other common tags include @throws, @example, and @deprecated.

Conclusion

Incorporating effective comments in JavaScript is not just a coding practice but a communication skill. It contributes significantly to the maintainability and scalability of code. By mastering JavaScript comments, you not only improve your code but also enhance your collaboration with others in the development process.

Remember, a well-commented code is a reflection of a thoughtful and professional developer. Embrace the power of commenting and watch your JavaScript code transform into a more accessible and maintainable asset.

Practice

Practice
What are true statements about JavaScript comments?
What are true statements about JavaScript comments?
Was this page helpful?