DEV Community

Cover image for "Happy Medium Commenting" in JavaScript
JS Bits Bill
JS Bits Bill

Posted on • Edited on

"Happy Medium Commenting" in JavaScript

Warning: this is an opinionated post! 😱

Having worked on a variety of front-end teams, I've observed a big difference of opinion on JavaScript commenting conventions. Everything from the practice of commenting every single function with a documentation generator from not commenting anything at all. I've found that there's a happy medium where we can comment only when necessary and still preserve clarity.

An important principle I think we sometimes forget is that we write code so that both the computer and human can understand it. But there should be more effort devoted towards the human - otherwise we'd all be naming our variables x, y, or z.

With that mind, you can name your functions, variables, classes, etc. with very clear names which can allow your reader to easily understand what your code is doing. If you do this correctly, the use of comments you'd use otherwise would be redundant.

While this is a highly subjective manner, I think it is possible to have situations where too many comments can damage readability. Take this example for instance:

// Add Mutation Observers for table subtotals
function addSubtotalObservers() {

  // Get all table elements
  const tables = document.querySelectorAll('.subscribe-table');

  // Loop through each table element
  tables.forEach(table => {

    // Get subtotal
    const subtotal = table.querySelector('.subtotal');

    // Create Mutation Observer callback on subtotal
    const observer = new MutationObserver(() => {
      // Disconnect to prevent infinite loop
      observer.disconnect();

      // Update subtotal total
      updateSubtableTotal(subtotal);
    });

    // Create Mutation Observer options
    const options = { attributes: true, childList: false };

    // Init Mutation Observer
    observer.observe(subtotal, options);
  });
}
Enter fullscreen mode Exit fullscreen mode

Here we've added a comment for every single line. If we remove virtually all of the comments, I'd wager 99% of readers who are familiar with JS and the DOM API would understand this function perfectly fine.

Let's redo this and only add a comment where it's truly important:

function addSubtotalObservers() {
  const tables = document.querySelectorAll('.subscribe-table');

  tables.forEach(table => {
    const subtotal = table.querySelector('.subtotal');

    const observer = new MutationObserver(() => {
      // Disconnect to prevent infinite loop
      observer.disconnect();
      updateSubtableTotal(subtotal);
    });

    observer.observe(subtotal, { attributes: true, childList: false });
  });
}
Enter fullscreen mode Exit fullscreen mode

I would argue this version improves readability. We can figure out what's going on from the naming itself, plus it's a shorter block that isn't bloating our file scroll depth.

Perhaps any comment here would be better off telling the reader why this function is necessary in the first place. But maybe the context of the script already makes that obvious. That's the crux in all of this - but the what of the function is what I'm emphasizing here.

But I really do think commenting can be abused. Take JSDoc for example. At a previous job, we adopted this standard and were supposed to use JSDoc's convention for every function:

/**
 * Callback for adding two numbers.
 *
 * @callback addNumsCallback
 * @param {int} sum - An integer.
 */

/**
 * Add 2 numbers together, then pass the results to a callback function
 *
 * @param {int} x - An integer.
 * @param {int} y - An integer.
 * @param {addNumsCallback} callback - A callback to run.
 */
function addNums(x, y, callback) {
  callback(x + y);
}
Enter fullscreen mode Exit fullscreen mode

Imagine doing that for every single function in your code. That's 14 lines of comments for 3 lines of code. 😬

Don't get me wrong, this kind of API-like commenting has it's place: like... documenting an API... but as a requirement to every block you write, I'd say this hurts more than it helps.

Programmer Ryan Mcdermott writes in his guide, Clean Code JavaScript, that "comments are an apology, not a requirement". In other words, comments should be used in places where you're sorry for having to do things a certain way, or apologizing for what could be perceived as a lack of clarity and righting the wrong with more detail. Otherwise, the way you write should make your intent clear.


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Top comments (0)