How to Write Single and Multi-Line Comments in JavaScript

Learn the complete syntax for writing single-line, multi-line, and documentation comments in JavaScript. Understand when to use each type and how comments affect code execution.

JavaScriptbeginner
8 min read

Comments are lines of text in your JavaScript code that the engine completely ignores during execution. They exist purely for human readers: to explain what the code does, why a particular approach was chosen, or to temporarily disable code during debugging. Every professional codebase uses comments, and knowing the syntax and conventions for writing them is a fundamental skill.

Think of comments as sticky notes attached to your code. The computer never reads them, but every person who opens the file does. A well-placed comment can save an hour of reverse-engineering; a missing comment on a complex algorithm can cost a team days of confusion.

JavaScript supports three styles of comments: single-line, multi-line, and JSDoc documentation blocks. This guide covers the syntax for each, when to use them, and how they interact with code execution.

Single-Line Comments with //

Single-line comments start with two forward slashes (//). Everything after // on that line is ignored by the JavaScript engine:

javascriptjavascript
// This is a single-line comment
const name = "Alice";
 
// Calculate the discount based on membership level
const discount = calculateDiscount(membership);
 
const tax = 0.08; // Tax rate for the current region

Single-line comments work in two positions:

  1. On their own line (above the code they describe)
  2. At the end of a line (inline, after the code)
javascriptjavascript
// Position 1: Above the code (most common)
// Validate that the user has an active subscription before proceeding
if (user.subscription.status === "active") {
  grantAccess(user);
}
 
// Position 2: End of line (for brief clarifications)
const MAX_RETRIES = 3; // Matches the API gateway timeout policy
const TIMEOUT_MS = 5000; // 5 seconds

What Happens During Execution

The JavaScript engine strips comments during the parsing phase, before any code runs. Comments have zero impact on performance:

javascriptjavascript
// This comment does not slow down your code
const x = 10; // Neither does this one
// Even a thousand comments have zero runtime cost
const y = 20;

Multi-Line Comments with /* */

Multi-line comments start with /* and end with */. Everything between these markers is ignored, even across multiple lines:

javascriptjavascript
/* This is a multi-line comment.
   It can span as many lines as needed.
   The engine ignores everything between the markers. */
const greeting = "Hello, World!";
javascriptjavascript
/*
  Configuration object for the payment gateway.
  All values are loaded from environment variables at startup.
  See docs/payment-setup.md for the full configuration reference.
*/
const paymentConfig = {
  apiKey: process.env.PAYMENT_API_KEY,
  merchantId: process.env.MERCHANT_ID,
  environment: process.env.NODE_ENV === "production" ? "live" : "sandbox"
};

Multi-Line Comment Formatting Conventions

Most codebases follow one of two formatting patterns for multi-line comments:

javascriptjavascript
// Style 1: Stars aligned on the left (most common)
/*
 * Handle the checkout process.
 * Validates the cart, applies discounts,
 * and processes the payment.
 */
function processCheckout(cart) {
  // ...
}
 
// Style 2: No leading stars (simpler)
/*
  Handle the checkout process.
  Validates the cart, applies discounts,
  and processes the payment.
*/
function processCheckout(cart) {
  // ...
}

Both are valid. Choose one and be consistent across your project.

Inline Multi-Line Comments

You can also use /* */ within a single line to comment out part of an expression:

javascriptjavascript
// Comment out one argument for testing
const result = calculate(width, /* height, */ depth);
 
// Temporarily change a value
const environment = /* "production" */ "development";
Multi-Line Comments Cannot Be Nested

JavaScript does not support nested multi-line comments. The first */ the engine encounters closes the comment, even if another /* appeared inside it. This can cause hard-to-find syntax errors when commenting out large blocks of code that already contain multi-line comments.

javascriptjavascript
/* This outer comment starts here
   /* This inner comment seems fine */
   but this text is no longer commented and causes a syntax error
*/

JSDoc Comments for Documentation

JSDoc comments are a special form of multi-line comments that start with /** (two stars after the slash). They are used to document functions, classes, and modules with structured annotations that editors and documentation tools can parse:

javascriptjavascript
/**
 * Calculate the total price including tax and discount.
 * @param {number} subtotal - The pre-tax, pre-discount amount
 * @param {number} taxRate - Tax rate as a decimal (e.g., 0.08 for 8%)
 * @param {number} [discount=0] - Optional discount amount to subtract
 * @returns {number} The final price rounded to 2 decimal places
 */
function calculateTotal(subtotal, taxRate, discount = 0) {
  const taxAmount = subtotal * taxRate;
  const total = subtotal + taxAmount - discount;
  return Math.round(total * 100) / 100;
}

JSDoc comments enable:

  • IntelliSense/autocomplete in editors like VS Code
  • Type checking when using TypeScript or JSDoc type annotations
  • Generated documentation with tools like JSDoc, TypeDoc, or Documentation.js
javascriptjavascript
/**
 * Represents a user in the system.
 * @typedef {Object} User
 * @property {string} name - Display name
 * @property {string} email - Email address
 * @property {string} role - One of "admin", "editor", "viewer"
 * @property {Date} createdAt - Account creation timestamp
 */
 
/**
 * Find a user by their email address.
 * @param {string} email - The email to search for
 * @returns {User|null} The matching user, or null if not found
 */
function findUserByEmail(email) {
  return users.find(u => u.email === email) || null;
}

Comment Types Comparison

FeatureSingle-Line (//)Multi-Line (/* */)JSDoc (/** */)
Spans multiple linesNoYesYes
Can be inlineYesYesRarely
NestableYes (each line)NoNo
Parsed by editorsNoNoYes
Generates docsNoNoYes
Best forQuick notes, TODOsBlock descriptionsFunction/class docs

Using Comments to Disable Code

Comments are frequently used during development to temporarily disable code:

javascriptjavascript
// Disable a single line
// console.log("Debug output:", data);
 
// Disable multiple lines
/*
validateUser(user);
sendNotification(user);
logActivity(user);
*/
 
// Disable part of an expression
const features = {
  darkMode: true,
  // notifications: true,  // Disabled until backend is ready
  analytics: false
};
Use Version Control, Not Comment Blocks

While commenting out code is useful during active development, do not leave large blocks of commented-out code in your committed files. Use Git to preserve old code and delete it from the working file. Commented-out code clutters the file and creates confusion about what is active. See the commenting best practices guide for more on this.

Special Comment Annotations

Several comment annotations have special meaning across JavaScript tools and teams:

javascriptjavascript
// TODO: Implement pagination for the user list
function getUsers() {
  return fetchAllUsers(); // Returns everything for now
}
 
// FIXME: This breaks when the array is empty
function getAverage(numbers) {
  return numbers.reduce((a, b) => a + b) / numbers.length;
}
 
// HACK: Workaround for browser bug in Safari 17
element.style.transform = "translateZ(0)";
 
// NOTE: This timeout matches the server-side session duration
const SESSION_TIMEOUT = 30 * 60 * 1000;
 
// WARNING: Changing this value requires a database migration
const MAX_USERNAME_LENGTH = 50;
 
// @ts-ignore - Suppress TypeScript error on next line
// @ts-expect-error - Expected TypeScript error on next line
AnnotationPurpose
TODOTask that needs to be done later
FIXMEKnown bug that needs fixing
HACKWorkaround that should be replaced
NOTEImportant context for understanding the code
WARNINGCautionary note about side effects or risks
@ts-ignoreSuppress TypeScript error (use sparingly)

Comments in HTML and CSS (Bonus Context)

Since JavaScript often lives alongside HTML and CSS, knowing the comment syntax for all three prevents confusion:

htmlhtml
<!-- This is an HTML comment -->
<script>
  // This is a JavaScript comment inside a script tag
  const x = 10;
</script>
csscss
/* This is a CSS comment */
.container {
  width: 100%; /* Inline CSS comment */
}
LanguageSingle-LineMulti-Line
JavaScript// comment/* comment */
HTMLN/A<!-- comment -->
CSSN/A/* comment */

Where to Place Comments

Strategic comment placement communicates intent without cluttering the code:

javascriptjavascript
// 1. File header: describe the module's purpose
/**
 * User authentication middleware.
 * Validates JWT tokens and attaches the user object to the request.
 * Requires AUTH_SECRET environment variable to be set.
 */
 
// 2. Before complex logic: explain WHY, not WHAT
// Use binary search instead of linear scan because the roster
// is sorted and can contain up to 50,000 entries
const index = binarySearch(roster, targetId);
 
// 3. Before regex patterns: always explain regex
// Match email format: local@domain.tld (RFC 5322 simplified)
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
 
// 4. Before magic numbers: explain the value
const EARTH_RADIUS_KM = 6371; // Mean radius in kilometers (WGS 84)
 
// 5. Before workarounds: explain the constraint
// Safari does not support the `gap` property in flexbox below v14.1
// Using margin-based spacing as a fallback

Best Practices

Writing Comments That Help

The goal of comments is to make code understandable. These practices ensure your comments add value rather than noise.

Comment the "why," not the "what." If your code is readable, the "what" is already clear. Comments should explain business rules, edge cases, performance decisions, and non-obvious constraints that the code alone cannot communicate.

javascriptjavascript
// Bad: restates the code
// Set count to 0
let count = 0;
 
// Good: explains the reason
// Reset count when switching tabs to prevent stale data accumulation
let count = 0;

Keep comments close to the code they describe. A comment that is separated from its code by blank lines or other statements becomes misleading. When the code changes, the orphaned comment stays and becomes wrong.

Update comments when you change the code. An outdated comment is worse than no comment at all. When refactoring, always check whether nearby comments still apply.

Use JSDoc for all exported functions. Any function that other modules import should have a JSDoc comment documenting its parameters, return value, and any side effects. This generates IntelliSense hints for every developer who uses the function.

Delete commented-out code before committing. Use Git to preserve old code. Commented-out code in committed files creates confusion about what is active and what is dead.

Common Mistakes and How to Avoid Them

Watch Out for These Pitfalls

Bad commenting habits reduce code readability instead of improving it.

Commenting obvious code. Adding // increment i by 1 above i++ wastes screen space and insults the reader. Only comment things that are not immediately obvious from reading the code.

Nesting multi-line comments. /* outer /* inner */ still in outer */ causes a syntax error because the first */ ends the entire comment. If you need to comment out a block that contains /* */ comments, use single-line comments (//) for each line instead.

Using comments instead of better naming. If you need a comment to explain what a variable does, consider renaming the variable instead:

javascriptjavascript
// Bad: needs comment
const d = 30; // days until expiration
 
// Good: self-documenting
const daysUntilExpiration = 30;

Writing comments in inconsistent style. Some files use // comment and others use /* comment */ for the same purpose. Pick a convention (single-line for brief notes, JSDoc for function docs, multi-line for block descriptions) and apply it consistently.

Leaving TODO comments indefinitely. TODO comments should be temporary. If a TODO has been in the codebase for months, either do it or remove it. Use your issue tracker for long-term tasks.

Next Steps

Learn JavaScript commenting best practices

Knowing the syntax is just the beginning. The commenting best practices guide covers when to comment, when not to, and how to write comments that genuinely help your team.

Set up JSDoc in your project

Configure your editor to parse JSDoc comments for IntelliSense. In VS Code, JSDoc works out of the box for JavaScript files. Try adding JSDoc comments to your most complex functions and see the improved autocomplete.

Practice reading code without comments

Open an open-source project on GitHub and read a file with all comments removed. Note which parts confuse you. Those are the spots where comments add real value.

Review your existing comments

Go through a recent project file and evaluate every comment. Does it explain "why"? Is it still accurate? Would better naming eliminate the need for it?

Rune AI

Rune AI

Key Insights

  • Single-line //: best for brief explanations and inline notes; everything after // on that line is ignored
  • Multi-line /* */: best for block descriptions and disabling code; cannot be nested
  • JSDoc /** */: structured documentation parsed by editors; use for exported functions and classes
  • Comment the "why": explain business rules, constraints, and non-obvious decisions, not what the code already says
  • Zero performance cost: comments are stripped during parsing and removed entirely by minifiers in production builds
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between // and /* */ comments in JavaScript?

The `//` syntax creates a single-line comment that extends from the `//` to the end of that line. The `/* */` syntax creates a multi-line comment that can span any number of lines between the opening `/*` and closing `*/`. Single-line comments are best for brief notes and inline explanations, while multi-line comments are better for block descriptions, file headers, and temporarily disabling multiple lines of code.

Do comments affect JavaScript performance?

No. Comments have zero impact on runtime performance. The JavaScript engine strips all comments during the parsing phase before any code executes. The only overhead is a negligible increase in file size before minification. Build tools like Terser, esbuild, and webpack automatically remove all comments from production bundles.

Can JavaScript comments be nested?

Single-line comments following each other on consecutive lines work fine. However, multi-line `/* */` comments cannot be nested. If you write `/* outer /* inner */ still outer */`, the first `*/` closes the entire comment, and the remaining text causes a syntax error. Use single-line `//` comments for each line if you need to comment out a block that already contains multi-line comments.

What are JSDoc comments and when should I use them?

JSDoc comments start with `/**` and use structured tags like `@param`, `@returns`, and `@typedef` to document functions, classes, and types. Use them for any function, class, or module that will be imported by other files. Editors like VS Code parse JSDoc comments to provide IntelliSense hints, parameter info, and type checking, making your code easier for other developers to use correctly.

Should I leave commented-out code in my files?

No. Commented-out code clutters files and creates confusion about what is active. Use version control (Git) to preserve old code. If you need to reference a previous implementation, check the Git history. The only exception is briefly commenting out code during active debugging, but always remove it before committing.

Conclusion

JavaScript provides three comment styles for different purposes: // for quick single-line notes, /* */ for multi-line descriptions, and /** */ for JSDoc documentation parsed by editors and tooling. The key to effective commenting is explaining why the code exists and why specific decisions were made, not restating what the code does. Keep comments close to the code they describe, update them when the code changes, and always delete commented-out code before committing.