JavaScript Comments

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.

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). This example uses a single line comment before each line, to explain the code:

HTML file: Displayed by browser:
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
  // Change heading:
     document.getElementById("myH").innerHTML = "My First Page";
  // Change paragraph:
     document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
<p><strong>Note:</strong>The comments are not executed.</p>
</body>

Note:The comments are not executed.

This example uses a single line comment at the end of each line, to explain the code:

HTML file: Displayed by browser:
<body>
<p id="demo"></p>
<script>
  var x = 5;  // Declare x, give it the value of 5
  var y = x + 2;  // Declare y, give it the value of x + 2
  document.getElementById("demo").innerHTML = y; // Write y to demo
</script>
<p><strong>Note:</strong> The comments are not executed.</p>
</body>

Note: The comments are not executed.


BackTable of ContentsNext