JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
The JavaScript comments are meaningful way to deliver message. It is used to add information about the 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.
There are mainly two advantages of JavaScript comments.
Single line comments start with //
.
Any text between //
and the end of the line will be ignored by JavaScript
(will not be executed).
This example uses a single-line comment before each code line:
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Multi-line comments start with /*
and end with */
.
Any text between /*
and */
will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";