How to Comment Code in JavaScript

Comments are essential in any programming language. Let’s see why they are useful and to whom they are helpful?

Why and When to Use Comments?

There are three areas where you want to use Comments:

1. Description of Code

Case 1: You wrote your code, and it went live. Suppose, after six months there is some Change Request, or Bug comes in for that code then it will be challenging for you understand it at first glance even if you had written it. So, in this case, comments would be helpful so you can understand what is going into that code.

Case 2: If you left the company, then it will be challenging for your replacement to understand your source code. So, if you have written proper description (in comments) for source code, then it will be easy for a new developer to understand it.

2. Commenting Source Code

It is not a good idea to take commented source code on production (live) servers. BUT comments are handy when you are in the development phase. You probably want to try new code without deleting already existed code, or if you wish to check-in part of the code and comment undone code, then you can use comments.

You also use comments if you don’t want to execute/run/compile your source code.

3. License & Version Information

Suppose you are distributing open-source code or license code than comments are beneficial to provide license information and version information on top of the source code. For example, look at the jQuery library code. You can see comments on the top of it.

Let’s see now types of comments are how to use comments to JavaScript.

How to Use Comments & Types

There are two types of comments. Single-line and Multi-line (or Block comments comments).

1. Single-line Comments

As the name suggests, if you want to Comment one line, then you can use this type of Comment. Below is the example.

// This is the text comment
// var a = b + c; 

As you can see in the above code, we have commented text and code with Single-line comment. Two forward slashes ( // ) we use for single-line Comment at the start of the text or code.

2. Multi-line or Block Comments

If you want to comment more than one line than instead of using Single-line comments multiple times for each line, you can use Multi-line or Block comments. It is useful if you want to comment long text or code. Below is the Example.

 /* Welcome to Tutorial Funda
   Learn Programming in Simple Way */

/* function Showalert() {  
      alert("Hello Tutorial Funda");  
    } */

In the above example, you can see that we have used forward slash followed by an asterisk ( /* ) to start block comment and end it with an asterisk followed by a forward slash ( */ ). This is how you can use multi-line or block comment.

That’s it. This is how we use comments in JavaScript.

Categories js

Subscribe Now!

Subscribe Us For Latest Articles