JavaScript Comment

Comment is the only way that another developers will understand your code, in most case we understand our previous or old code by reading the useful comment we had writen. either we want to make some correction or debugging.

Use comments in JavaScript for improving code readability, explaining complex logic, and providing insights into the code's functionality. Here, we'll discuss the best practices for writing good comments in JavaScript, along with examples.

Javascript supports two types of comments as we have seen in the previous chapter. The first one is double-slashes (//)tell javascript to ignore everything to the end of the line. You will see them used most often to describe what is happening on a particular line.


var x = 5; // Everything from the // to end of line is ignored(*)
var price = 123.45; // 2 times the price of a whatsit.

Block quotes begin a comment block with a slash-asterisk /*and Javascript will ignore everything from the start of the comment block until it encounters an asterisk-slash /*.Block quotes are useful for temporally disabling large areas of code, or describing the purpose of a function, or detailing the purpose and providing credits for the script itself.


function add(a, b){ 
  /* this function will take 
  two argument and return the sum of them. 
  And this is the example of multiple line comment */
  return a + b;
}

You should note that while comments are useful for maintaining the code, they are a liability itself in Javascript since they will be transmitted along with the code to each and every page load, which can create substantial bandwidth penalties and increase the load time of your page for users.

This doesn't mean you shouldn't comment your code, just that once your code is "finished" you should make a backup copy with the comments, then strip out all the comments in the file which is actually sent to the user.

Let's explain how to write a good comment on your code that should benefit the reviewer or other developers. Please consider reading the below intutive example.

Use Comments Sparingly

Comments should be used to explain why something is being done, not what is being done. The code itself should ideally be self-explanatory.

// Bad example: This function adds two numbers
function add(a, b){ 
  return a + b;
}

// Good example: Calculate the total price including tax
function calculateTotalPrice(price, taxRate){ 
  return price * ( 1 + taxRate);
}

Comment Complex Logic

If a piece of code involves complex algorithms or logic, it's crucial to provide comments explaining the reasoning behind it.

// Bad example: Performing a series of calculations
var result = (a * b) / (c - d) + e * f;

// Good example: Calculate the net profit
var netProfit = (revenue - expenses - taxes) / totalMonths;

Document Function Purpose and Parameters

Comments should accompany function declarations to describe their purpose, expected parameters, and return values.

// Bad example: Function to calculate square of a number
function square(num){ 
  return num * num;
}

// Good example: Calculate the area of a rectangle
function calculateRectangleArea(length, width){
  // Multiply length by width to get area
  return length * width;
}

Update Comments Alongside Code Changes

Whenever you make changes to your code, ensure that you update any relevant comments to reflect those changes accurately.

// Bad example: Outdated comment
var  totalPrice = calculateTotalPrice (100, 1.0); // Calculate total price with 10% tax

// Good example: Updated comment
var  totalPrice = calculateTotalPrice = (100, 1.0); // Calculate total price with 10% tax and discount

Avoid Redundant Comments

Comments should add value to the codebase. Avoid adding comments that merely restate what the code is doing.

// Bad example: Incrementing the counter
var counter  = 0;// Initialize counter variable
counter++;// Increment counter by 1

// Good example: Initialize and increment counter
var counter  = 0;
counter++;

Use Comments to Temporary Disable Code

Comments should accompany function declarations to describe their purpose, expected parameters, and return values.

// Bad example: Deleting code for testing purposes
// function foo() {
//   // Code here
// }

// Good example: Commenting out code temporarily
function foo(){
  // Temporary disable code for testing
  // ...
}

Example

<html>
<head>
  <title>Title</title>
</head>
<body>
  <div id="feedback"></div>
  <script>
    var counter  = 0;
    counter++;
    document.getElementById("feedback").innerHTML= counter
  </script>
</body>
</html>

By following these practices, you can ensure that your JavaScript code remains well-documented, making it easier for you and other developers to understand, maintain, and debug.