JavaScript comments can be used to explain JavaScript code and make it easier to read. JavaScript comments can also be used to prevent execution when testing alternative code.
Comments can be done in following two ways:
- Single Line Comments
- Multi-line Comments
Single Line Comments
Commenting out a line starting with //. Any text after // till the end of the line will be ignored by JavaScript (will not be executed). This example uses a one-line comment before each line of code:
// Change the paragraph text:
document.getElementById("userP").innerHTML = "My paragraph text has been changed.";
//more
let name = "code Config"; // declare & assign name
let price=10.50 // declare and assign Price
Multi-line Comments
Multiline comments begin with /* and end with */. Any text between /* and */ will be ignored by JavaScript. This example uses multiline comments (comment blocks) to explain the code:
/*
Below code will change
the paragraph text and
old text will get replaced with
this new text. Thanks!
*/
document.getElementById("userP").innerHTML = "My sample paragraph on Code config website.";
Use Comments to Prevent Execution
Using comments to prevent code execution is appropriate for code testing. Adding // in front of a line of code changes the line of code from an executable line to a comment.
This example uses // to prevent one of the lines of code from executing:
// document.getElementById("myH").innerHTML = "Change my page Header.";
document.getElementById("userP").innerHTML = "My sample paragraph on Code config website.";
If you want to prevent multiple lines form execution, then use the following:
/*
document.getElementById("myH").innerHTML = "Change my page Header.";
document.getElementById("userP").innerHTML = "My sample paragraph on Code config website.";
*/
Nutshell, it is most common to use single line comments rather than multiple lines. Block comments are often used for formal documentation of the product or specific class.