How to Use Comments Efficiently in JavaScript

ref: Dharmen Shah's Blog, Bits and Pieces

Single-line Comments

let p= 3.14; // The value of Pi (ฯ€)

Multi-line Comments

/**
 * Standard
 * Multi-line
 * Comment
 */

Code tells how and comments tells why
the code should be able to self-explain how it works, keeping comments to address why itโ€™s there in the first place.

// Do
let p = 3.14; // Rounded value of Pi
let c = 2 * p * 10; // Calculate the circumference of a circle with 

// Don't
let p = 3.14; // Initiate the value of the variable p
let c = 2 * p * 10 // Multiply the value p into 20

Avoid Abbreviations

Short formPreferred full form
akaalso known as
i.e."that is" or "to be specific"
e.g.for example
viz."in other words" or "namely"

When should I use comments?

  • Prefacing
    • Prefacing or explaining the code is one of the main goals of using comments
  • For Debugging
    • Since the JavaScript engine does not interpret commented-out codes, we can use comments for debugging purposes
    • if there is an error in your code, you can comment out code lines and re-run the code to see which line is causing the error
  • Tagging
    • Most commonly used keywords for tag: TODO, BUG or FIXME (a known bug that should be corrected), UNDONE (a reversal or roll back of previous code), HACK (a workaround)
          /**
           * ...
           * TODO:
           * - [x] task 1
           * - [ ] task 2
           */
      
  • Store Metadata
    • we can include information author, version, repo links within metadata
          /**
           * Represents a book.
           * @author FN LN <hey@fnln.me>
           * @version 1.2.3
           * @see {@link http://github.com|GitHub}
           * @since 1.0.1
           * ...
           */
          function Book(title, author) {}
      

In VS Code, you just need to type /** and it will create the closing tag vs-code-comment-javascript

Plugin Document This is helpful when you want to generate comments based on your function plugin-docthis

Plugin Better Comments helps to highlight comments plugin-better-comments