Start learning free

LESSON 3 OF 410 · WELCOME TO JAVASCRIPT

Comments in JavaScript

Lesson Read the full explanation

TL ; DR:

  • Comments are lines of code that JavaScript will intentionally ignore (not execute). They don't do anything.


  • You add a single line comment in JavaScript by typing // followed by any text:

    // This is a comment!
    console.log("This is not!");
    


Full lesson:

Comments are lines of code that JavaScript will intentionally ignore. They don't do anything.

They're just used to create notes for yourself and others about what the code does.

There are two types of code comments in JavaScript:


1. Single line comments:

We create single line comments by typing // and JavaScript will ignore (not execute) any text between // and the end of the line.

Single line comments automatically end at the next line of code:

// Next line will greet the user:
console.log("Hello user!");

Output of this code:

Hello user!

We can also use single line comments at the end of a line to explain the code:

console.log("Hello user!"); // This line greets the user
console.log("This is not a comment!");

Output of this code:

Hello user!
This is not a comment!

2. Multi-line comments:

We can also comment multiple lines of code using multi-line comments.

We type /* to begin the comment and type */ to end the comment:

/* This is a 
multi-line comment
console.log("This will not run");
Next line will greet the user:
*/

console.log("Hello user!");

Output of this code:

Hello user!

Assignment
Follow the Coding Tutorial and let's write some comments!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · WELCOME TO JAVASCRIPT

    Comments in JavaScript, explained

    Introduction

    In this lesson, we will explore the concept of comments in JavaScript. Comments are an essential part of programming as they help developers understand the code better. They are especially useful for documenting the purpose of code blocks, explaining complex logic, and leaving notes for future reference. Comments are ignored by the JavaScript engine, meaning they do not affect the execution of the code.

    Understanding the Basics

    Comments in JavaScript come in two forms: single-line comments and multi-line comments. Understanding these basics is crucial as they form the foundation for writing clear and maintainable code.

    Single-line Comments

    Single-line comments start with // and extend to the end of the line. They are useful for brief explanations or notes.

    // This is a single-line comment
    console.log("Hello, World!"); // This prints a message to the console
    

    Multi-line Comments

    Multi-line comments start with /* and end with */. They can span multiple lines and are useful for longer explanations or temporarily disabling blocks of code.

    /* This is a multi-line comment
       It can span multiple lines
       console.log("This will not run");
    */
    console.log("Hello, World!");
    

    Main Concepts

    Let's delve deeper into the key concepts and techniques for using comments effectively in JavaScript.

    Documenting Code

    Comments are primarily used to document code. This includes explaining the purpose of functions, variables, and complex logic. Well-documented code is easier to understand and maintain.

    // Function to add two numbers
    function add(a, b) {
      return a + b; // Return the sum of a and b
    }
    

    Disabling Code

    Comments can be used to temporarily disable code during debugging or testing. This helps in isolating issues without deleting the code.

    // console.log("This line is disabled");
    console.log("This line is active");
    

    Examples and Use Cases

    Here are some examples demonstrating the use of comments in various contexts.

    Example 1: Explaining Code

    // Calculate the area of a rectangle
    function calculateArea(width, height) {
      // Multiply width and height to get the area
      return width * height;
    }
    console.log(calculateArea(5, 10)); // Output: 50
    

    Example 2: Debugging

    // Debugging a function
    function greet(name) {
      // console.log("Entering greet function");
      return "Hello, " + name + "!";
    }
    console.log(greet("Alice")); // Output: Hello, Alice!
    

    Common Pitfalls and Best Practices

    While comments are helpful, there are common pitfalls to avoid and best practices to follow.

    Common Pitfalls

    • Over-commenting: Adding too many comments can clutter the code and make it harder to read.
    • Outdated comments: Ensure comments are updated when the code changes to avoid confusion.

    Best Practices

    • Be concise: Write clear and concise comments that add value.
    • Keep comments relevant: Ensure comments are directly related to the code they describe.

    Advanced Techniques

    For advanced users, comments can be used in conjunction with documentation tools like JSDoc to generate comprehensive documentation for your codebase.

    /**
     * Adds two numbers together.
     * @param {number} a - The first number.
     * @param {number} b - The second number.
     * @return {number} The sum of a and b.
     */
    function add(a, b) {
      return a + b;
    }
    

    Code Implementation

    Here is a well-commented code snippet demonstrating the use of comments in a real-world scenario.

    // Function to calculate the factorial of a number
    function factorial(n) {
      // Base case: if n is 0, return 1
      if (n === 0) {
        return 1;
      }
      // Recursive case: multiply n by the factorial of n-1
      return n * factorial(n - 1);
    }
    console.log(factorial(5)); // Output: 120
    

    Debugging and Testing

    Comments can aid in debugging and testing by providing context and explanations for the code. Here are some tips:

    • Use comments to mark sections of code: This helps in quickly locating and isolating issues.
    • Write test cases: Document the purpose of each test case using comments.
    // Test case for the add function
    console.log(add(2, 3)); // Expected output: 5
    

    Thinking and Problem-Solving Tips

    When approaching problems related to comments, consider the following strategies:

    • Break down complex problems: Use comments to outline the steps needed to solve the problem.
    • Practice regularly: Write code and add comments to improve your understanding and documentation skills.

    Conclusion

    In this lesson, we covered the importance of comments in JavaScript, the different types of comments, and best practices for using them. Comments are a powerful tool for writing clear, maintainable, and well-documented code. Practice using comments in your code to enhance your programming skills.

    Additional Resources

    For further reading and practice, check out the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free