19
76

How to write JavaScript comments

Reading Time: 2 minutes

No matter ES5 or ES6, we will still need to use JavaScript comments to improve the understanding of our written codes. This will help newbies who look at your code base to have a better understanding of the logic flow.

Types of JavaScript Comments

  • Single line comment
  • Multi-line comment

Single line comment

Single line comment means only a line of code will not be executed. It is indicated by have double slash ‘//’ to indicate the start of the comment. This means that comment can start at any position after ‘//’. Once you go to the next line, JavaScript will interpret them as code again.

// We are starting the comment immediately at the beginning of the line

let numberOfApple = 5; // This comment starts after the code ends

Multi-line comment

Multi-line comment is where you intend to write some description that will take a few lines and do not want to use ‘//’. One of the reason is the usage of ‘//’ may results in a long comment creating some bugs if that line is uncommented.

Hence. Multi-line comment is a block of comment where we will use ‘/*’ to indicate the start of the comment and ‘*/’ to indicate the end of the comments. Be careful to close it correctly or else everything will become a comment till the end of the file.

/*
Here are all the comments.
Here are all the comments.
Here are all the comments.
*/
const someLongFunction = () => {

};

Structuring comments in code

There are a few reasons why we add comments in the code

  • Describe logic that needs additional explanation like special notes
  • Help readers know an overview of a class component or function
  • Comment codes temporary that will be usable later

Let’s look at an example of writing comments

// This is the inventory size
let currentFruitCount = 100;

/*
This functions will return the results of whether the fruit seller will sell the fruit quantity to the buyer or not.
The input quantity should always be more than 0.
*/
const sellOrNot = (quantity) => {

  // Limit the minimum and maximum count from 1 to 10
  if (quantity < 1 || quantity > 10) {
    return false;
  } 

  // Compare the quantity ordered with the stock available
  if (quantity > currentFruitCount) {
    return false;
  }

  // Since sufficient quantity, sell and reduce inventory
  currentFruitCount = currentFruitCount - quantity;
  return true;
};

Conclusion

Comments can be very useful! If it is a small explanation, single line comment will be good enough. Else, multi-line comment will be recommended.

More reference here!

Show Comments

No Responses Yet

Leave a Reply