01 / 20
//

Writing Comments
in JavaScript

Learn to write comments that explain intent and assumptions, making your code readable, maintainable, and collaborative.

JavaScript

What Is a Comment?

A comment is text inside your source code that the JavaScript engine completely ignores at runtime. Comments exist solely for human readers: your future self, teammates, and code reviewers.

// Single-Line
Everything after // until the end of the line is ignored.
/* */ Multi-Line
Everything between /* and */ is ignored, even across lines.

Comment Syntax at a Glance

SINGLE-LINE COMMENT const tax = price * 0.08 ; // 8% sales tax for Texas ignored by the engine MULTI-LINE COMMENT /* Calculate compound interest. Assumes annual compounding. */

Why Comments Matter

Code tells the computer what to do. Comments tell humans why the code does it. Without comments, even brilliant code becomes a mystery in six months.

✓ Readability
New team members understand your logic without guessing.
✓ Maintainability
Future-you can fix bugs faster when intent is documented.
✓ Collaboration
Code reviews go smoother when assumptions are stated upfront.

The Golden Rule of Commenting

✕ WHAT it does // increment i by 1 i ++; Already obvious from the code itself ✓ WHY it does it // Move to the next retry // attempt (max 3 allowed) i ++; Explains intent and the business constraint

Intent vs. Assumptions

Intent
The purpose behind a block of code: what goal it achieves in the bigger picture.
Assumptions
Conditions the code relies on being true: input ranges, formats, external states.
// Intent: Prevent duplicate charges when the user
// rapidly clicks "Pay" multiple times.
// Assumes: payBtn exists in the DOM at load time.
payBtn.addEventListener("click", () => {
  payBtn.disabled = true;
  processPayment();
});

Good vs. Bad Comments

Scenario ✕ Bad Comment ✓ Good Comment
Variable assignment // set x to 10 // Default retry limit per API docs
Conditional check // if age is greater than 18 // Users under 18 need parental consent
Loop // loop through array // Batch emails in groups of 50 to avoid rate limit
Function call // call fetchData // Assumes auth token is still valid (expires in 1h)

How to Write Effective Comments

1
Read the code aloud. If the "why" is not obvious, write a comment.
2
State the intent. What goal does this code serve in the larger feature?
3
Document assumptions. What must be true about inputs, state, or environment?
4
Flag edge cases. Warn about known limits, workarounds, or browser quirks.
5
Keep it current. Update or delete comments whenever the code changes.

Example 1: Basic Intent Comment

// Ensure the username is lowercase so lookups
// in our case-sensitive database are consistent.
const normalized = username.toLowerCase();

Example 2: Documenting Assumptions

/*
* Sort products by price ascending before rendering.
* Assumes: each product object has a numeric `price`
* field. Items with missing prices are filtered out
* upstream by validateProducts().
*/
products.sort((a, b) => a.price - b.price);

Example 3: Edge Cases and Workarounds

// HACK: Safari < 15 fires resize events when the
// on-screen keyboard appears. We debounce by 300ms
// so the layout does not thrash. Remove this once
// Safari 15+ reaches 95%+ market share.
let resizeTimer;
window.addEventListener("resize", () => {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(handleResize, 300);
});

Function-Level Documentation

For public or complex functions, use a JSDoc-style block comment above the function. This helps editors show tooltips and lets tools auto-generate documentation.

/**
* Calculate the total price after applying a discount.
* Assumes price and discount are non-negative numbers.
* @param {number} price - Original price in USD.
* @param {number} discount - Fraction off (0 to 1).
* @returns {number} Final price, never below 0.
*/
function applyDiscount(price, discount) {
  return Math.max(0, price * (1 - discount));
}

When to Use Inline vs. Block

// Inline
Quick clarification for a single line: magic numbers, flags, short rationale.
/* */ Block
Multi-sentence explanation above a section or function: intent, assumptions, caveats.
/** */ JSDoc
Structured docs for public APIs: parameters, return types, examples.

Common Mistakes

✕ Restating the Code
Writing "// add 1 to counter" above counter++ adds zero new information.
✕ Stale Comments
Changing the code but forgetting to update the comment creates misleading documentation.
✕ Over-Commenting
Commenting every single line obscures the important notes and creates noise.
✕ No Comments at All
Leaving tricky logic unexplained forces readers to reverse-engineer your thinking.

Comment Cheat Sheet

Question to Ask If Yes, Comment Should...
Why does this code exist? State the intent
What must be true for it to work? State the assumption
Is there a non-obvious edge case? Explain the edge case
Is this a temporary workaround? Tag with HACK or TODO
Is the code self-explanatory? Skip the comment

Question 1 of 5

Which comment best explains intent for the line
user.age >= 18?

Question 2 of 5

What is wrong with the comment // set x to 5 placed above let x = 5;?

Question 3 of 5

Which syntax correctly creates a multi-line comment in JavaScript?

Question 4 of 5

A teammate changed a function's logic but left the old comment untouched. This creates a:

Question 5 of 5

Which comment best documents an assumption?