Documentation
Rationale
Comprehensive documentation helps developers understand, maintain, and extend code. It reduces onboarding time, prevents misunderstandings, and improves collaboration.
JSDoc Standards
Use JSDoc to document all functions, classes, and modules. Proper documentation improves code readability, IDE support, and team collaboration.
- Document the purpose of each function or class.
- List all parameters and their types.
- Specify the return type and describe what is returned.
Example:
/**
* Get the user's name.
* @param {boolean} capitalize Whether to capitalize the name or not. Defaults to true.
* @return {string} The formatted full name of the user.
*/
function getUserName(capitalize = true) {
// ...
}
Advanced Examples:
/**
* Registers a new user.
* @param {Object} data - User data
* @param {string} data.email - User email
* @param {string} data.password - User password
* @return {Promise<User>} The created user object
*/
async function registerUser(data) {
// ...
}
/**
* UserManager class for user operations.
*/
class UserManager {
/**
* Authenticates a user.
* @param {string} email
* @param {string} password
* @return {boolean}
*/
authenticate(email, password) {
// ...
}
}
- Use JSDoc for modules, classes, functions, and complex objects.
- Document edge cases, default values, and side effects.
Inline Comments
Use comments to explain complex or non-obvious code. Place comments above the code they describe.
Advanced Examples:
// Good: Explain why, not what
// Use a fallback if the API call fails due to network issues
let data;
try {
data = await fetchData();
} catch (e) {
// Fallback to cached data
data = getCachedData();
}
// Bad: Redundant or outdated
let count = 0; // set count to zero
- Place comments above the code they describe.
- Update comments when logic changes.
API Documentation
- Use tools like JSDoc, Docdash, or Swagger for generating API docs.
- Document endpoints, request/response formats, authentication, and error codes.
- Keep API docs in sync with implementation.
Example Workflow:
- Annotate code with JSDoc comments.
- Run
jsdocto generate HTML documentation. - Review and update docs as part of code reviews.
Best Practices
- Keep documentation up to date with code changes.
- Document public interfaces, expected inputs/outputs, and side effects.
- Use consistent terminology and formatting.
- Encourage team members to contribute to documentation.
- Review and update documentation during code reviews and merges.
- Provide usage examples for complex APIs and modules.
- Use consistent terminology and formatting across all docs.
- Encourage team members to contribute and improve documentation.