How to properly comment JavaScript code

Properly commenting JavaScript code is essential for enhancing code readability, facilitating collaboration, and making it easier to understand the code’s functionality. Here are some guidelines and examples for effectively commenting JavaScript code:

1. Single-line Comments: Use // to add comments that span a single line.

// This is a single-line comment 
var variable = 10; // Comment at the end of the line

2. Multi-line Comments: Enclose multi-line comments with /* at the beginning and */ at the end.

/*
This is a multi-line comment
It can span multiple lines
*/

3. Commenting Functionality: Describe the purpose, inputs, outputs, and any relevant details about a function.

// Calculate the sum of two numbers
// Parameters: num1 - the first number, num2 - the second number
// Returns: The sum of num1 and num2
function calculateSum(num1, num2) {
  return num1 + num2;
}

4. Commenting Classes: Explain the purpose and functionality of a class, its properties, and methods.

// Represents a person with a name and age
class Person {
  /**
   * @param {string} name - The person's name.
   * @param {number} age - The person's age.
   */
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  /**
   * Get the person's name.
   * @returns {string} The person's name.
   */
  getName() {
    return this.name;
  }

  /**
   * Get the person's age.
   * @returns {number} The person's age.
   */
  getAge() {
    return this.age;
  }
}

5. Commenting Variables: Clarify the purpose of variables, especially if their names may not be self-explanatory.

var counter = 0; // Keep track of the number of iterations
var flag = false; // Indicates whether the process is complete

6. Commenting Complex Logic: Describe complex logic or algorithms to help readers understand the intention behind the code.

// Loop through the array and find the first even number
// If no even number is found, return -1
for (var i = 0; i < arr.length; i++) {
  if (arr[i] % 2 === 0) {
    return arr[i];
  }
}
return -1;

7. Commenting Troubleshooting or Temporary Code: Add comments to debug or explain temporary code that may need attention in the future.

// TODO: Handle edge case when the array is empty
// TODO: Refactor this section to improve performance
// DEBUG: Print the value of the variable for debugging

Remember that comments should be concise, meaningful, and add value to the code. They should explain the why, not just the what. Avoid excessive commenting for self-explanatory code. Keep your comments up to date as you modify your code to maintain accuracy.

Leave a comment