4. Commenting on obvious things

Most comments can be replaced with names of variables and functions. Before you write a comment, remember this.

For example, code like this:

// This function sums only odd numbers in an array
const sum = (val) => {
  return val.reduce((a, b) => {
    if (b % 2 === 1) { // If the current number is odd
      a+=b;            // Add current number to accumulator
    }
    return a;          // The accumulator
  }, 0);
};

You can replace it with this:

const sumOddValues = (array) => {
  return array.reduce((accumulator, currentNumber) => {
    if (isOdd(currentNumber)) { 
      return accumulator + currentNumber;
    }
    return accumulator;
  }, 0);
};

But sometimes you can only clarify the code with a comment. In that case, focus on the question: "WHY this code is needed," not "WHAT this code does. Here's an example of code where comments only clutter up the code:

// create a variable and initialize it to 0
let sum = 0;
// Loop over array
array.forEach(
  // For each number in the array
  (number) => {
    // Add the current number to the sum variable
    sum += number;
  }
);

Don't do that if you are a programmer. And if you are the employer of such programmers, fire them right now.

Last updated