Documentation Comments
-
Rule: JSDoc should be used for documenting functions, classes, and methods.
-
Reason: JSDoc provides a standardized way to document your code, which helps improve maintainability by making it easier to understand how functions and classes work. It also allows for better integration with IDEs and tools to enhance developer productivity.
Example:
/**
* Calculates the total price including tax.
* @param {number} price - The original price.
* @param {number} taxRate - The tax rate to apply.
* @returns {number} The total price including tax.
*/
function calculateTotal(price, taxRate) {
return price * (1 + taxRate);
}
Type Annotations with JSDoc
-
Rule: Where TypeScript is not used, leverage JSDoc for type annotations to indicate parameter and return types for better editor IntelliSense.
-
Reason: JSDoc type annotations help provide editor integration with features like autocompletion, type checking, and inline documentation, even in plain JavaScript projects.
Inline Comments for “Why” Not “What”
-
Rule: Inline comments should be used sparingly and only when necessary to explain why something is being done, not what is being done.
-
Reason: The code itself should be self-explanatory. Inline comments should focus on explaining why a decision was made (e.g., why a certain algorithm is used) rather than stating the obvious.
Example (Correct):
// Use a separate loop for the final processing to avoid modifying the array while iterating
for (let i = 0; i < array.length; i++) {
// Processing logic here
}
Example (Incorrect):
let total = 0; // Total is initialized to zero
for (let i = 0; i < array.length; i++) { // Loop through the array
total += array[i];
}
Generate Documentation
-
Rule: Utilize tools like jsdoc to generate HTML documentation websites from your JSDoc comments.
-
Reason: Generating documentation from comments helps maintain up-to-date API documentation automatically, which is especially useful for large teams or projects with multiple contributors.
Command to generate documentation:
Summary:
-
Documentation: Use JSDoc for documenting functions, classes, and methods, and inline comments to explain the "why", not the "what".
-
Type Annotations: Use JSDoc for type annotations where TypeScript is not available to improve editor IntelliSense.
-
Generate Documentation: Utilize tools like jsdoc to generate HTML documentation directly from JSDoc comments.