BLOG POSTS
    MangoHost Blog / How to Write Comments in JavaScript – Best Practices
How to Write Comments in JavaScript – Best Practices

How to Write Comments in JavaScript – Best Practices

Writing clear, effective comments in JavaScript is one of those skills that separates amateur code from professional-grade applications. Good commenting practices make your code maintainable, help team members understand complex logic, and save countless hours when you’re debugging at 2 AM six months from now. This guide covers everything from basic syntax to advanced documentation strategies, plus the pitfalls that can turn helpful comments into technical debt.

How JavaScript Comments Work

JavaScript supports two primary comment syntaxes that serve different purposes. Single-line comments use the double slash notation and are perfect for quick explanations or temporarily disabling code:

// This is a single-line comment
let userAge = 25; // Comments can also follow code on the same line

// Temporarily disable this feature
// sendAnalyticsData(userData);

Multi-line comments use the slash-asterisk syntax and work well for longer explanations, function documentation, or commenting out entire code blocks:

/*
This is a multi-line comment
that spans several lines
*/

/*
function complexCalculation(data) {
    // This entire function is commented out
    return data.reduce((acc, val) => acc + val.weight * val.multiplier, 0);
}
*/

The JavaScript engine completely ignores commented text during execution, making comments zero-cost from a performance perspective. However, they do increase file size, which matters for client-side applications where every byte counts.

Step-by-Step Implementation Guide

Let’s walk through implementing a comprehensive commenting strategy for a real JavaScript project. Start with these foundational practices:

Step 1: Document Function Purpose and Parameters

/**
 * Calculates compound interest for investment planning
 * @param {number} principal - Initial investment amount
 * @param {number} rate - Annual interest rate (as decimal, e.g., 0.05 for 5%)
 * @param {number} time - Investment period in years
 * @param {number} compoundFreq - Compounds per year (default: 12)
 * @returns {number} Final amount after compound interest
 */
function calculateCompoundInterest(principal, rate, time, compoundFreq = 12) {
    // A = P(1 + r/n)^(nt) - standard compound interest formula
    return principal * Math.pow((1 + rate / compoundFreq), compoundFreq * time);
}

Step 2: Explain Complex Business Logic

function processUserPermissions(user, resource) {
    // Check if user has direct access first (fastest path)
    if (user.permissions.includes(resource.id)) {
        return true;
    }
    
    // Fall back to role-based permissions
    // This handles inherited permissions from user groups
    const userRoles = user.roles || [];
    const resourceRoles = resource.requiredRoles || [];
    
    // Using some() instead of nested loops for better performance
    return userRoles.some(role => resourceRoles.includes(role));
}

Step 3: Document Workarounds and Edge Cases

function sanitizeFileName(filename) {
    // Remove characters that cause issues on Windows filesystems
    // Specifically targeting: < > : " | ? * and control characters
    let cleaned = filename.replace(/[<>:"|?*\x00-\x1f]/g, '');
    
    // Windows reserved names that need special handling
    const reservedNames = ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'LPT1'];
    if (reservedNames.includes(cleaned.toUpperCase())) {
        cleaned = `_${cleaned}`; // Prefix with underscore to make valid
    }
    
    return cleaned;
}

Real-World Examples and Use Cases

Here are practical examples showing how proper commenting transforms code readability in production scenarios:

API Integration with Error Handling

async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        
        // API returns 404 for deleted users, but we want to handle gracefully
        if (response.status === 404) {
            return { error: 'User not found', isDeleted: true };
        }
        
        if (!response.ok) {
            // Log the actual error but don't expose internal details to client
            console.error(`API Error: ${response.status} - ${response.statusText}`);
            throw new Error('Failed to fetch user data');
        }
        
        return await response.json();
    } catch (error) {
        // Network errors, JSON parsing errors, etc.
        // Re-throw with context for higher-level error handling
        throw new Error(`User data fetch failed: ${error.message}`);
    }
}

Performance-Critical Code Documentation

function optimizedSearch(data, searchTerm) {
    // Early return for empty search - avoids unnecessary processing
    if (!searchTerm || searchTerm.length < 2) {
        return data;
    }
    
    // Convert to lowercase once instead of in every comparison
    // This optimization saves ~40% execution time on large datasets
    const lowerSearchTerm = searchTerm.toLowerCase();
    
    // Using filter with pre-computed lowercase values
    // Benchmarked: ~2.3ms for 10k records vs ~4.1ms with inline toLowerCase()
    return data.filter(item => 
        item.searchableText.toLowerCase().includes(lowerSearchTerm)
    );
}

Comment Types Comparison

Different commenting approaches serve different purposes. Here’s a breakdown of when to use each:

Comment Type Best Use Case Example Scenario Maintenance Impact
Single-line (//) Quick explanations, temporary disabling Explaining a complex regex or math formula Low – easy to update
Multi-line (/* */) Block commenting, longer explanations Describing algorithm approach or business rules Medium – requires attention to formatting
JSDoc (/** */) Function/class documentation, API docs Public APIs, complex functions with parameters High – must stay synchronized with code
TODO/FIXME Technical debt tracking Known issues or planned improvements High – creates maintenance obligations

Best Practices and Common Pitfalls

Essential Best Practices:

  • Comment the “why,” not the “what” – Explain business logic and decisions rather than obvious code operations
  • Keep comments close to relevant code – Avoid large comment blocks separated from the code they describe
  • Update comments when code changes – Outdated comments are worse than no comments
  • Use consistent formatting – Establish team standards for comment structure and style
  • Leverage JSDoc for public APIs – Tool integration provides automatic documentation generation

Critical Pitfalls to Avoid:

// BAD: Stating the obvious
let count = 0; // Set count to zero

// GOOD: Explaining purpose or context  
let count = 0; // Track failed retry attempts for rate limiting

// BAD: Outdated information
function calculateTax(amount) {
    // Apply 8% sales tax (this was changed to 8.5% months ago)
    return amount * 1.085;
}

// GOOD: Current and contextual
function calculateTax(amount) {
    // Using current state sales tax rate - update when tax law changes
    const TAX_RATE = 0.085;
    return amount * (1 + TAX_RATE);
}

Advanced Documentation Patterns:

/**
 * Custom event emitter with memory leak prevention
 * Automatically removes listeners after maxListeners threshold
 * 
 * @example
 * const emitter = new SafeEventEmitter({ maxListeners: 100 });
 * emitter.on('user-action', handleUserAction);
 * 
 * @see {@link https://nodejs.org/api/events.html|Node.js Events Documentation}
 */
class SafeEventEmitter extends EventEmitter {
    constructor(options = {}) {
        super();
        this.maxListeners = options.maxListeners || 50;
        
        // Periodically clean up listeners to prevent memory leaks
        // This addresses a common issue in long-running applications
        this.cleanupInterval = setInterval(() => {
            this.removeOldListeners();
        }, 300000); // Every 5 minutes
    }
}

Modern development tools can automatically generate documentation from well-formatted comments. Tools like JSDoc and TypeDoc parse comment blocks to create comprehensive API documentation, making the investment in good commenting practices pay dividends in project maintainability.

Performance Considerations for Production:

Comments don’t affect runtime performance, but they do impact bundle size. For client-side applications, consider using build tools like Terser or Webpack to automatically strip comments during production builds:

// webpack.config.js optimization
module.exports = {
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    format: {
                        comments: false, // Remove all comments in production
                    },
                },
            }),
        ],
    },
};

The key to effective JavaScript commenting lies in striking the right balance between helpful context and code clarity. Focus on explaining complex business logic, documenting APIs thoroughly, and maintaining consistency across your codebase. Remember that the best comment is often the one that helps a developer understand not just what the code does, but why it exists and how it fits into the larger system architecture.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked