JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JavaScript Comments
JavaScript comments describe the JavaScript code and make it more readable.
JavaScript comments prevent execution when testing alternative code.
Single-Line Comments
Single line comments
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
This example defines a single-line comment before each code line:
Example
// Change heading:
document.getElementById(“myH”).innerHTML = “JavaScript Comments”;
// Change paragraph:
This example defines a single line comment at the end of each line to explain the code:
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
// Write y to demo:
Multi-line Comments
Multi-line comments begin with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example defines a multi-line comment (a comment block) that explains the code:
Example
/*
The code below will change
the heading with id = “myH”
and the paragraph with id = “myP”
*/
Using Comments to Prevent Execution
The comments are used to prevent the execution of code suitable for code testing.
Adding // in front of a code line changes the code lines from an executable line to comment.
This example makes use // to prevent execution of one of the code lines:
Example
<script>
//document.getElementById(“myH”).innerHTML = “My First Page”;
document.getElementById(“myP”).innerHTML = “My first paragraph.”;
</script>
<p>The line starting with // is not executed.</p>
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id=”demo”></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById(“demo”).innerHTML =
“The value of z is: ” + z;
</script>
</body>
</html>