JavaScript comments can be used to improve code readability.
JavaScript does not execute comments.
We can add comments to explain the JavaScript, or to improve the readability of the code.
Single-line comments begin with //.
example
The following example uses single-line comments to explain the code:
// output title: document.getElementById("myH1").innerHTML="Welcome to my Homepage"; // output paragraph: document.getElementById("myP").innerHTML="This is my first paragraph.";
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 code will output
a heading and a paragraph
and will represent the start of the home page
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
Use annotations to block execution
Example 1
In the example below, a comment is used to prevent execution of one of the lines of code (useful for debugging):
//document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
Example 2
In the example below, comments are used to prevent the execution of the code block (which can be used for debugging):
/*
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/
Use comments at the end of lines
In the following example, we put the comment at the end of the code line:
example
var x=5; // declare x and assign 5 to it var y=x+2; // declare y and assign x+2 to it