JavaScript comments

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.";

try it yourself

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.";

try it yourself

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.";

try it yourself

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.";
*/

try it yourself

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326942915&siteId=291194637