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.
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:
// 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 regionSingle-line comments work in two positions:
- On their own line (above the code they describe)
- At the end of a line (inline, after the code)
// 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 secondsWhat Happens During Execution
The JavaScript engine strips comments during the parsing phase, before any code runs. Comments have zero impact on performance:
// 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:
/* 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!";/*
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:
// 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:
// 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.
/* 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:
/**
* 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
/**
* 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
| Feature | Single-Line (//) | Multi-Line (/* */) | JSDoc (/** */) |
|---|---|---|---|
| Spans multiple lines | No | Yes | Yes |
| Can be inline | Yes | Yes | Rarely |
| Nestable | Yes (each line) | No | No |
| Parsed by editors | No | No | Yes |
| Generates docs | No | No | Yes |
| Best for | Quick notes, TODOs | Block descriptions | Function/class docs |
Using Comments to Disable Code
Comments are frequently used during development to temporarily disable code:
// 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:
// 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| Annotation | Purpose |
|---|---|
TODO | Task that needs to be done later |
FIXME | Known bug that needs fixing |
HACK | Workaround that should be replaced |
NOTE | Important context for understanding the code |
WARNING | Cautionary note about side effects or risks |
@ts-ignore | Suppress 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:
<!-- This is an HTML comment -->
<script>
// This is a JavaScript comment inside a script tag
const x = 10;
</script>/* This is a CSS comment */
.container {
width: 100%; /* Inline CSS comment */
}| Language | Single-Line | Multi-Line |
|---|---|---|
| JavaScript | // comment | /* comment */ |
| HTML | N/A | <!-- comment --> |
| CSS | N/A | /* comment */ |
Where to Place Comments
Strategic comment placement communicates intent without cluttering the code:
// 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 fallbackBest 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.
// 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:
// 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
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
Frequently Asked Questions
What is the difference between // and /* */ comments in JavaScript?
Do comments affect JavaScript performance?
Can JavaScript comments be nested?
What are JSDoc comments and when should I use them?
Should I leave commented-out code in my files?
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.
Tags
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.