JavaScript Comments

A comment is text in your source code that the JavaScript engine completely ignores when it runs your program. Comments exist purely for humans: they let you explain what a piece of code does, why it does it that way, or temporarily switch off a line of code while you’re debugging. Every professional codebase relies on comments to stay readable, and learning to use them well is one of the fastest ways to make your own code easier for others — and for future you — to understand.

Overview: How Comments Work

JavaScript supports two kinds of comments: single-line comments and multi-line (block) comments. Both are handled at the very first stage of how your code is processed. Before the JavaScript engine parses your code into an executable structure, it runs a step called tokenization (or lexical analysis), which breaks the raw source text into meaningful pieces called tokens — keywords, identifiers, operators, string literals, and so on. Comments are recognized and discarded during this tokenization step. They never become tokens, so they never reach the parser, and they have absolutely zero effect on how your program runs or how fast it runs.

This matters for a few practical reasons:

  • Comments add no runtime cost. You can write as many as you need without worrying about performance.
  • Because comments are stripped before parsing, you can “comment out” code — turn working code into an inert comment — and the engine will behave exactly as if that code were deleted.
  • Comments are purely textual. The engine does not understand or validate anything inside a comment, which is both convenient (you can write anything) and dangerous (a comment can quietly describe behavior that no longer matches the real code, since nothing keeps them in sync).

Tools built for JavaScript, like documentation generators (JSDoc), linters, and IDEs, do sometimes read specially formatted comments to provide extra features such as autocomplete hints or generated API docs. But that’s an added layer built on top — as far as the core language is concerned, a comment is simply invisible.

Syntax

There are two comment forms:

// This is a single-line comment. It runs from // to the end of the line.

/*
  This is a multi-line (block) comment.
  It can span as many lines as you like,
  and ends at the closing */
Form Starts with Ends with Typical use
Single-line // end of the current line Short notes, inline explanations, quickly disabling one line
Multi-line /* */ Longer explanations, disabling blocks of code, file/function headers
JSDoc (a special multi-line form) /** */ Documenting functions, parameters, and return values for tools and IDEs

A single-line comment can appear on its own line, or after code on the same line (an “inline” or “trailing” comment). A multi-line comment can appear anywhere a single-line comment can, but it can also be placed in the middle of a line of code, since it has a defined end point rather than running to the end of the line.

Examples

Example 1: Basic comment placement

// This is a single-line comment
const greeting = "Hello, world!"; // inline comment explaining the variable

/*
  This is a multi-line comment.
  It can explain something in more detail
  across several lines.
*/
console.log(greeting);
Output:
Hello, world!

Both comment styles are removed before the code runs, so only the console.log call actually executes. Notice that the inline comment after const greeting = "Hello, world!"; does not affect the statement at all — the engine simply stops reading once it hits //.

Example 2: Using comments to disable code while debugging

function calculateTotal(price, quantity) {
  const subtotal = price * quantity;
  // const tax = subtotal * 0.08; // tax calculation temporarily disabled for testing
  const total = subtotal; // + tax, once tax is re-enabled
  return total;
}

console.log(calculateTotal(10, 3));
Output:
30

This is one of the most common real-world uses of comments: quickly switching off a line of logic without deleting it. Here the tax calculation line has been “commented out,” so calculateTotal returns the plain subtotal (10 * 3 = 30) instead of a total with tax added. Because the disabled code is still there in text form, it’s easy to re-enable later by removing the //.

Example 3: Documenting a function with a JSDoc-style comment

/**
 * 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 area of the rectangle.
 */
function getRectangleArea(width, height) {
  return width * height;
}

console.log(getRectangleArea(4, 5));
console.log(getRectangleArea(2.5, 6));
Output:
20
15

A comment that starts with /** (two asterisks) is still just an ordinary block comment as far as JavaScript itself is concerned — the extra asterisk has no special meaning to the engine. But editors like VS Code and documentation tools like JSDoc recognize this pattern and use the @param and @returns tags to show you helpful tooltips and autocomplete hints while you’re calling the function elsewhere in your code.

Under the Hood: What the Engine Actually Does

When the JavaScript engine (such as V8, the engine inside Node.js and Chrome) reads your source file, it goes through it character by character looking for patterns it recognizes. Here’s what happens step by step when it encounters comment syntax:

  • The tokenizer scans forward through the source text, and the moment it sees the two characters //, it switches into “skip mode” and ignores every character until it reaches a line terminator (a newline character).
  • If it instead sees /*, it switches into a different skip mode and ignores everything — including line breaks — until it finds the matching */.
  • Once the comment has been skipped, tokenization resumes as normal from the very next character.
  • The resulting token stream handed to the parser contains no trace of the comment at all — it’s as if the text was never there.

Because block comments are found by scanning for the first closing */, they do not nest. If you write a block comment containing another opening /* inside it, the comment actually ends at the first */ found, and any leftover text after that is treated as real code — which will almost always cause a syntax error. This trips up a lot of beginners who assume block comments nest the way parentheses or curly braces do; they don’t.

Common Mistakes

Mistake 1: Nesting block comments

Writing something like /* This is /* a nested */ comment */ looks reasonable, but it isn’t. The first */ the engine finds — the one right after “nested” — closes the comment. Everything after that, including the trailing comment */, is parsed as actual JavaScript code, which usually breaks the program with a syntax error. If you need to temporarily disable a block of code that already contains block comments (for example, JSDoc comments above functions), use single-line comments on every line instead, or wrap the whole section using an editor’s “toggle comment” feature, which is smart enough to avoid this trap.

// Disable each line individually instead of nesting /* */ blocks
function oldHelper(value) {
  // return value * 2;
  // return value + 1;
  return value;
}

console.log(oldHelper(10));
Output:
10

Mistake 2: Forgetting to close a multi-line comment

If you open a block comment with /* and forget the closing */, every line of code after it — potentially the rest of the file — gets silently swallowed into the comment and never runs. This is a sneaky bug because you won’t get an error about a missing closing tag directly; instead you’ll just notice that functions you expected to run seem to have vanished, or you’ll eventually get a syntax error much further down the file where a stray */ from something else finally closes it. Always double-check that every /* has a matching */, and lean on your editor’s syntax highlighting — it will usually color the “missing close” region differently so the problem is easy to spot.

/*
  TODO: revisit this configuration later
*/
const config = { retries: 3, timeout: 1000 };
console.log(config);
Output:
{ retries: 3, timeout: 1000 }

This version closes the comment correctly, so the config object is declared and logged as expected. Leaving off that closing */ would have made the const config = ... line (and possibly more) disappear into the comment.

Best Practices

  • Comment the why, not the what. Code already shows what it does; a good comment explains a reason, trade-off, or non-obvious constraint that the code alone can’t communicate.
  • Keep comments up to date. An outdated comment that contradicts the code is worse than no comment at all, because it actively misleads the next reader.
  • Prefer clear variable and function names over heavy commenting. If you find yourself writing a comment to explain what a poorly named variable holds, rename the variable instead.
  • Use // for short, local notes and quick debugging toggles; reserve /* */ for longer explanations or documentation blocks above functions and modules.
  • Use the /** ... */ JSDoc style for public functions, especially in libraries or shared code, so editors can show helpful parameter and return type hints to anyone calling your function.
  • Use consistent markers like // TODO: or // FIXME: for follow-up work — many editors and linters can highlight or list these automatically.
  • Avoid leaving large chunks of commented-out “dead” code sitting in a file long-term. Source control (like Git) already preserves history, so old code is better deleted than accumulated as comments.
  • Don’t over-comment obvious code. A comment like “increment i by 1” above i++; adds noise without adding understanding.

Practice Exercises

  • Exercise 1: Write a script with a variable called userAge set to a number. Add a single-line comment above it explaining what the variable represents, and an inline comment after a console.log statement noting what gets printed.
  • Exercise 2: Write a function divide(a, b) that returns a / b. Add a JSDoc-style block comment above it describing the parameters and return value, then call the function and log the result.
  • Exercise 3: Write a small script with three console.log statements. Use single-line comments to “disable” two of them so that only one actually runs, then verify the output only shows the message from the remaining active line.

Summary

  • JavaScript has two comment forms: single-line (//, runs to end of line) and multi-line/block (/* ... */, runs until the closing marker).
  • Comments are removed during tokenization, before parsing, so they add zero runtime cost and have no effect on execution.
  • Block comments do not nest — the first */ encountered always closes the comment, which can cause confusing syntax errors if you try to nest them.
  • Comments are commonly used to explain reasoning, temporarily disable code while debugging, and (in JSDoc form) document functions for tooling and IDEs.
  • Good comments explain why, stay in sync with the code, and don’t substitute for clear naming; outdated or excessive comments do more harm than good.