Annotation specification
Comments are an essential part of code readability and maintainability. Well-defined commenting standards help teams collaborate efficiently and reduce comprehension costs, especially in a flexible and dynamic language like JavaScript.
Single-Line Comment Standards
Single-line comments start with double slashes //
, with a space between the symbols and the comment content. Suitable for brief code explanations or temporary debugging:
// Calculate the total user score
const totalScore = user.scores.reduce((a, b) => a + b, 0);
// TODO: Performance optimization needed
function processData() { /* ... */ }
Special cases:
- When comments appear at the end of a code line, leave at least two spaces between the code and the comment:
const threshold = 0.8; // System default threshold
- For consecutive single-line comments forming a comment block, maintain alignment:
// Initialize configuration parameters
// These values will be overridden at runtime
// Defaults are only for development
const config = loadDefaults();
Multi-Line Comment Standards
Multi-line comments use the /** ... */
format, typically for file headers or function descriptions:
/**
* Generates a random integer within a specified range
* @param {number} min - Minimum value (inclusive)
* @param {number} max - Maximum value (inclusive)
* @returns {number} Random integer
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Key elements:
- The opening
/**
and closing*/
should each occupy their own line. - Each comment line starts with
*
and is aligned. - Use
@param
tags for parameter descriptions and@returns
for return values.
JSDoc Comment Standards
JSDoc is the standard documentation system for JavaScript, supporting type checking and IDE intelligence:
/**
* User account class
* @class
* @property {string} username - Login username
* @property {Date} registerDate - Registration date
*/
class UserAccount {
/**
* @constructor
* @param {Object} options - Initialization options
* @param {string} options.username - Must include @ symbol
* @param {number} [options.age=18] - Optional age parameter
*/
constructor(options) {
/** @private */
this._token = generateToken();
}
}
Common tag examples:
@type {string}
Type definition@typedef {Object} UserProfile
Custom type@deprecated
Marks deprecated methods@throws {Error}
Possible thrown errors
Special Comment Markers
Standardized comments for specific scenarios:
- Debugging markers:
// FIXME: Async callback may cause memory leaks
function fetchData() {
// DEBUG: Temporary log output
console.log(data);
}
- Task management:
// TODO: Need to implement caching
// HACK: Temporary workaround, pending refactor
- Conditional compilation (with build tools):
/* #if ENV === 'development' */
mockAPI();
/* #endif */
Module Comment Standards
For ES modules or CommonJS modules, add module-level comments:
/**
* User authentication module
* @module auth
* @description Provides login/logout/permission validation
* @author team@example.com
* @version 1.2.0
*/
/**
* Validates JWT token
* @param {string} token - Token to validate
* @returns {Promise<boolean>}
*/
export async function verifyToken(token) { /* ... */ }
Comment Content Guidelines
- Avoid redundant comments:
// Bad example
let count = 0; // Set count to 0
// Good example
// Reset vote counter
let count = 0;
- Explain why, not what:
// Using bitwise operation instead of Math.floor for performance
const index = value >> 0;
- Complex algorithm comments:
// Using Floyd's cycle-finding algorithm to detect linked list loops
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
Comments and Type Systems
When combined with TypeScript or Flow types:
interface Pagination {
/** Current page number, starting from 1 */
current: number;
/**
* Items per page
* @default 10
*/
pageSize?: number;
}
/**
* Paginated query result
* @template T
*/
type PageResult<T> = {
data: T[];
total: number;
};
Comment Toolchain
-
Documentation generation:
- JSDoc
- TypeDoc
- ESDoc
-
Code quality checks:
// .eslintrc.json { "rules": { "valid-jsdoc": ["error", { "requireReturn": false, "prefer": { "returns": "return" } }] } }
-
IDE integration:
- VS Code's Document This plugin
- WebStorm's JSDoc autocompletion
Comments and Version Control
In Git repositories, note:
- Avoid committing
console.log
comments for debugging - Clean up implemented
TODO
comments promptly - Use
@since
to mark version changes:
/**
* New encryption algorithm
* @since v2.1.0
* @deprecated Use encryptV3 instead
*/
function encryptV2() {}
Comment Code Smells
Signs of comments needing refactoring:
- Commented-out obsolete code blocks
- Outdated comments that don't match implementation logic
- Long explanations of "what this is" (indicates code should be refactored)
- Emotional content (e.g., "This bug is so stupid!")
// Anti-pattern example
// This function was written by John in 2015, no idea why it's implemented this way
// But modifying it causes production issues, so DON'T TOUCH!
function magicCalculation() {
/* Mysterious logic */
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn