JavaScript Comments
JavaScript comments can be used to improve code readability.
JavaScript Comments
JavaScript does not execute comments.
We can add comments to explain JavaScript or to improve code readability.
Single-line comments start with //.
This example uses single-line comments to explain the code:
Example
//
Output a heading:
document
.
getElementById
(
"
myH1
"
)
.
innerHTML
=
"
Welcome to my homepage
"
;
//
Output a 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 code outputs a heading and a paragraph and represents the start of the homepage
*/
document
.
getElementById
(
"
myH1
"
)
.
innerHTML
=
"
Welcome to my homepage
"
;
document
.
getElementById
(
"
myP
"
)
.
innerHTML
=
"
This is my first paragraph.
"
;
Try it »
Using Comments to Prevent Execution
In the following example, a comment is used to prevent the execution of one of the lines of code (useful 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, a comment is used to prevent the execution of a block of code (useful for debugging):
Example
/*
document.getElementById("myH1").innerHTML="Welcome to my homepage"; document.getElementById("myP").innerHTML="This is my first paragraph.";
*/
Try it »
Using Comments at the End of a Line
In the following example, we place comments at the end of code lines:
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 »