Geek Slack

Introduction to JavaScript
    About Lesson



    JavaScript Comments


    JavaScript Comments

    Comments are used to explain code and make it more readable. They can also be used to prevent execution when testing alternative code.

    1. Single-line Comments

    Single-line comments start with //. Any text between // and the end of the line is ignored by JavaScript (will not be executed).

    Example:

    // This is a single-line comment
    var x = 5; // This is another single-line comment

    2. Multi-line Comments

    Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by JavaScript.

    Example:

    /*
    This is a multi-line comment
    It spans multiple lines
    */
    var y = 10;
    
    /* This is another multi-line comment
       that starts and ends on the same line */
    var z = 15;

    3. Using Comments for Debugging

    Comments are often used to temporarily disable code for debugging purposes.

    Example:

    var total = 0;
    // total = total + 1;
    total = total + 5;
    console.log(total); // Output will be 5

    4. Best Practices for Comments

    Good comments explain “why” something is done, not “what” is done. The code itself should be self-explanatory as to “what” is done.

    Here are some tips for writing good comments:

    • Keep comments concise and to the point.
    • Update comments if you update your code.
    • Use comments to explain complex logic.

    Example:

    // Calculate the factorial of a number
    function factorial(n) {
        // If n is 0, its factorial is 1
        if (n === 0) {
            return 1;
        }
        // Otherwise, recursively calculate the factorial
        return n * factorial(n - 1);
    }

    By following these guidelines, you can make your code more understandable and maintainable.