JavaScript Comments

Back to JS page

Table of Contents

Single Line Comments

Single line comments start with //.

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

Single-line comments before each code line to explain the code:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Single Line Comments</h4>
<p id="demo"></p>

<script>
// Change heading
document.getElementById("demo").innerHTML = "Your first name";
// Change paragraph
document.getElementById("demo").innerHTML = "Peter";
</script>

</body>
</html>

Example 1

Result View Example

Multi-line Comments

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:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Multi-line Comments</h4>
<p id="demo"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
let x = 5;
let y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

Example 2

Result View Example

Using Comments to Prevent Execution

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

Adding // in front of a code line changes the code lines from an executable line to a comment.

This example uses // to prevent execution of one of the code lines, and uses a comment block to prevent execution of multiple lines:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Using Comments to Prevent Execution</h4>
<p id="demo1"></p>
<p id="demo2"></p>

<script>
//document.getElementById("demo1").innerHTML = "This line is commented out";
document.getElementById("demo1").innerHTML = "Hello Dolly!";

/*
document.getElementById("demo2").innerHTML = "This is block commented out";
document.getElementById("demo2").innerHTML = "Also block commented out";
*/
document.getElementById("demo2").innerHTML = "Only this runs!";
</script>

</body>
</html>

Example 3

Result View Example

Document

Document in project

You can Download PDF file.

Reference