JS Comments
JavaScript code can be made more understandable and explained with the use of comments.
When testing alternative code, JavaScript comments can also be used to stop the code from running.
Single Line Comments
Comments in single lines begin with //.
JavaScript won’t execute any content that appears between // and the end of the line.
Every code line in this example has a one-line comment before it:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
The code in this example is explained with a single line remarks at the end of each line:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments
Comments with multiple lines begin with /* and conclude with */.
JavaScript will ignore any text that is between /* and */.
In order to show the code, this example employs a multi-line remark, or comment block:
Example
/*
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.";
Single line comments are usually used.
Formal documentation frequently uses block comments.
Using Comments to Prevent Execution
Code testing can benefit from the use of comments to stop code from running.
A code line that has // in front of it becomes a comment and not an executable line.
In this example, one of the code lines keeps from running by using //:
Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
In this example, the working of multiple lines is avoided by using a comment block:
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/