Comments & Code Style
Code is read far more often than it is written, so the way you comment and format it matters as much as whether it runs. Good comments explain why something is done, not what the code obviously does, and consistent style lets any reader scan a file without friction. This page covers JavaScript’s two comment syntaxes, JSDoc for structured documentation, the naming conventions the community has settled on, and how semicolons and automatic insertion actually work.
Writing comments
JavaScript has two comment forms. A line comment starts with // and runs to the end of the line. A block comment is wrapped in /* */ and can span multiple lines. Use line comments for short notes and block comments when you need a paragraph or want to temporarily disable a chunk of code.
// Single-line comment: explain a non-obvious decision
const RETRY_LIMIT = 3; // inline comment, aligned to the right
/*
Block comment for a longer explanation.
Use this when one line isn't enough.
*/
function fetchUser(id) {
// Early-return guard keeps the happy path un-indented
if (!id) return null;
return db.users.find(id);
}
The best comments add information the code cannot. Avoid restating the obvious (i++; // increment i); instead capture intent, edge cases, or links to context.
Tip: Treat
// TODO:and// FIXME:as searchable markers. Most editors and linters surface them, turning your comments into a lightweight task list.
JSDoc basics
JSDoc is a structured comment format that documents functions, parameters, and return values. It starts with /** (note the double asterisk) and uses @ tags. Editors like VS Code read JSDoc to power autocomplete and inline hints, and tools can generate HTML docs or even type-check plain JavaScript from it.
/**
* Calculate the total price including tax.
*
* @param {number} amount - Pre-tax amount in dollars.
* @param {number} [rate=0.08] - Tax rate as a decimal.
* @returns {number} The total rounded to two decimals.
*/
function withTax(amount, rate = 0.08) {
return Math.round(amount * (1 + rate) * 100) / 100;
}
console.log(withTax(100)); // default rate
console.log(withTax(100, 0.2)); // custom rate
Output:
108
120
The square brackets around [rate=0.08] mark the parameter as optional with a default. Common tags include @param, @returns, @throws, @deprecated, and @example.
Naming conventions
JavaScript naming follows a few well-established casing rules. Sticking to them signals intent: a reader can tell a constant from a class from a variable at a glance.
| Convention | Used for | Example |
|---|---|---|
camelCase | Variables, functions, methods | userName, getTotal() |
PascalCase | Classes, constructors, components | UserAccount, OrderForm |
UPPER_SNAKE_CASE | True constants, config flags | MAX_RETRIES, API_URL |
#name | Private class fields | #balance |
const MAX_LOGIN_ATTEMPTS = 5; // module-level constant
class PaymentProcessor { // PascalCase for the class
#secretKey; // private field
chargeCard(amount) { // camelCase method
const transactionId = crypto.randomUUID();
return { transactionId, amount };
}
}
Prefer descriptive names over abbreviations (elapsedMs beats e), and name booleans as questions (isActive, hasPermission). Reserve UPPER_SNAKE_CASE for values that are genuinely fixed at author time, not every const.
Semicolons and ASI
JavaScript has Automatic Semicolon Insertion (ASI): the parser inserts semicolons at certain line breaks so many statements work without them. ASI is reliable most of the time, but a few cases bite. A line that starts with (, [, `, +, -, or / may be joined to the previous line, and a return followed by a newline returns undefined.
// Dangerous: ASI does NOT insert a semicolon here
const total = subtotal + tax
[1, 2, 3].forEach(log) // parsed as subtotal + tax[1,2,3]...
// return on its own line returns undefined
function broken() {
return
{ ok: true }; // never reached
}
console.log(broken()); // undefined
Output:
undefined
Warning: Whether you use semicolons everywhere or rely on ASI, be consistent. Tools like Prettier and ESLint enforce one style automatically and eliminate the edge cases above.
Readability tips
Beyond comments and naming, small formatting habits keep code legible: consistent two-space indentation, blank lines to separate logical groups, short focused functions, and braces even on one-line if statements. Let a formatter handle the mechanical parts so reviews focus on logic, not whitespace.
// Hard to scan
if(x>0)doThing();else doOther();
// Clear and consistent
if (x > 0) {
doThing();
} else {
doOther();
}
Best Practices
- Comment the why, not the what — the code already shows what it does.
- Use JSDoc on public functions so editors and teammates get inline documentation.
- Pick one naming convention per kind of identifier and apply it everywhere.
- Adopt a formatter (Prettier) and a linter (ESLint) to enforce style automatically.
- Decide on semicolons as a team and stay consistent to avoid ASI surprises.
- Keep functions small and names descriptive; delete dead code instead of commenting it out.
- Remove stale comments — an outdated comment is worse than none.