Best Practices in Code Documentation and Formatting
Learn the essentials of using JSDoc, and effective commenting, along with indentation and formatting best practices.
Effective documentation and consistent formatting are key to making code readable and maintainable. This guide covers the usage of JSDoc and the dos and don’ts of commenting and formatting.
/** * Adds two numbers together. * @param {number} a - The first number. * @param {number} b - The second number. * @returns {number} The sum of the two numbers. */function sum(a, b) { return a + b;}
/** * This function calculates the total price of an order * including tax and discount. It applies a tax rate of 8%, * and a discount rate is applied if applicable. * * @param {number} basePrice - The base price of the order. * @param {boolean} hasDiscount - Indicates if the order has a discount. * @returns {number} The total price after applying tax and discount. */function calculateTotalPrice(basePrice, hasDiscount) { const taxRate = 0.08; let discount = 0; if (hasDiscount) { discount = basePrice * 0.1; // 10% discount } return basePrice + (basePrice * taxRate) - discount;}
/* This function calculates the price. It has parameters. It returns a number.*/function calculateTotalPrice(basePrice, hasDiscount) { // The actual function code}// Non-informative, redundant comments
Including Meaningful Comments & Avoiding Redundancy
Strategic comments enhance code clarity, but beware of redundancy. Prioritize meaningful insights to facilitate collaboration and understanding among developers.
// Start a loopusers.forEach(user => { // Check if the user is eligible for discount if (user.isEligibleForDiscount()) { // Apply discount to the user applyDiscount(user); }});// Redundant comments that simply restate the code
Copy
// Calculate areafunction calculateArea(l, w) { return l * w; // Ambiguous and unhelpful comment}
Inconsistent naming conventions, brace styles, or line breaks.Remember, the goal of these practices is to make your code as clear and maintainable as possible. Well-documented and formatted code not only benefits you but also your fellow developers who may work on your code in the future.