JavaScript Comments

The JavaScript comments are meaningful way to deliver message. It is used to explain JavaScript code, warnings or suggestions so that end user can easily interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

JavaScript comments can also be used to prevent execution, when testing alternative code.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

  • To make code easy to understand It can be used to elaborate the code so that end user can easily understand the code.
  • To avoid the unnecessary code It can also be used to avoid the code being executed. Sometimes, we add the code to perform some action. But after sometime, there may be need to disable the code. In such case, it is better to use comments.

Types of JavaScript Comments

There are two types of comments in JavaScript:

  • Single-line Comment
  • Multi-line Comment

JavaScript Single line Comment

It is represented by double forward slashes (//). It can be used before and after the statement.

// It is single line comment
document.write("JavaScript Single line Comment");

Single-line comment added after the statement.

var a=20;
var b=30;
var x=a+b;//It adds values of a and b variable
document.write(x);//prints sum of 20 and 30

JavaScript Multi line Comment

It can be used to add single as well as multi line comments. So, it is more convenient.

/* your code here  */

It can be used before, after and middle of the statement.

/* It is multi line comment.
It will not be displayed */
document.write("Javascript multiline comment");

Using Comments to Prevent Execution

Using comments to prevent execution of code, are suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line to a comment.

//document.getElementById("fl").innerHTML = "Welcome to Fastlearning";
document.getElementById("js").innerHTML = "Welcome to JavaScript Tutorial";

Share this article on