阿里云主机折上折
  • 微信号
Current Site:Index > Annotation specification

Annotation specification

Author:Chuan Chen 阅读数:25433人阅读 分类: JavaScript

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:

  1. The opening /** and closing */ should each occupy their own line.
  2. Each comment line starts with * and is aligned.
  3. 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:

  1. Debugging markers:
// FIXME: Async callback may cause memory leaks
function fetchData() {
  // DEBUG: Temporary log output
  console.log(data);
}
  1. Task management:
// TODO: Need to implement caching
// HACK: Temporary workaround, pending refactor
  1. 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

  1. Avoid redundant comments:
// Bad example
let count = 0; // Set count to 0

// Good example
// Reset vote counter
let count = 0;
  1. Explain why, not what:
// Using bitwise operation instead of Math.floor for performance
const index = value >> 0;
  1. 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

  1. Documentation generation:

    • JSDoc
    • TypeDoc
    • ESDoc
  2. Code quality checks:

    // .eslintrc.json
    {
      "rules": {
        "valid-jsdoc": ["error", {
          "requireReturn": false,
          "prefer": { "returns": "return" }
        }]
      }
    }
    
  3. 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:

  1. Commented-out obsolete code blocks
  2. Outdated comments that don't match implementation logic
  3. Long explanations of "what this is" (indicates code should be refactored)
  4. 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

上一篇:函数定义规范

下一篇:代码缩进与格式

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.