JavaScript Comments


JavaScript comments can be used to improve the readability of the code.


JavaScript Comments

JavaScript will not execute comments.

We can add comments to explain the JavaScript or improve the readability of the code.

Single-line comments begin with // .

This example uses single-line comments to explain the code:

Example

// Output title:
document.getElementById("myH1").innerHTML="Welcome to my homepage";
// Output paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";

 Try It! 


JavaScript Multi-line Comments

Multi-line comments start with /* and end with */ .

The following example uses multi-line comments to explain the code:

Example

/*
The following codes will output a heading and a paragraph, and will represent the beginning of the homepage
*/
document.getElementById("myH1").innerHTML="Welcome to my homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";

 Try It! 


Use Comments to Prevent Execution

In the following example, comments are used to prevent the execution of one of the lines of code (which can be used for debugging):

Example

// document.getElementById("myH1").innerHTML="Welcome to my homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";

 Try It! 

In the following example, comments are used to prevent the execution of code blocks (which can be used for debugging):

Example

/*
document.getElementById("myH1").innerHTML="Welcome to my homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/

 Try It! 


Use Comments At The End of The Line

In the following example, we put the comment at the end of the code:

Example

var x=5; // declare x and assign 5 to it
var y=x+2; // declare y and assign x+2 to it

 Try It!