JavaScript Comments

JavaScript comments are used to explain JavaScript code and enhance its readability.

JavaScript comments can also be used to prevent execution when testing alternative code.

Single-line comments

Single-line comments are used to // Start.

any located // Any text between the comment and the end of the line will be ignored by JavaScript (will not be executed).

This example uses single-line comments before each line of code:

Example

// Change title:
 document.getElementById("myH").innerHTML = "My first page";
// Change paragraph:
 document.getElementById("myP").innerHTML = "My first paragraph.";

Try It Yourself

This example uses single-line comments at the end of each line to explain the code:

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 Yourself

Multi-line comments

Multi-line comments are used to /* at the beginning, with */ at the end.

any located /* and */ between the text will be ignored by JavaScript.

This example uses multi-line comments (comment blocks) to explain the code:

Example

/*
 the following code will change
 in the web page
 the title with id = "myH"
 and the paragraph with id = "myP":
*/
document.getElementById("myH").innerHTML = "My first page";
document.getElementById("myP").innerHTML = "My first paragraph."; 

Try It Yourself

Comment:Single-line comments are the most common.

Tip:Comment blocks are often used for official statements.

Using comments to prevent execution

Using comments to prevent code execution is very suitable for code testing.

by adding // will change executable code lines to comments.

This example uses // to prevent the execution of a code line:

Example

//document.getElementById("myH").innerHTML = "My first page";
document.getElementById("myP").innerHTML = "My first paragraph."; 

Try It Yourself

This example uses a comment block to prevent the execution of multi-line code:

Example

/*
document.getElementById("myH").innerHTML = "My first page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/

Try It Yourself

Supplementary Reading

Advanced JavaScript Tutorial: ECMAScript Syntax