JavaScript Comments
Single Line Comments
Short comments on one line begin with //
.
Any text between the //
and the end of the line won't be used by JavaScript (won't be done).
In this example, a brief note is placed before each line of code, all on a single line.
In this illustration, we employ a brief comment placed at the end of every line to clarify the code.
Multi-line Comments
Multi-line comments in HTML begin with /* and end with */.
JavaScript will not pay attention to any text enclosed between /*
and */
.
It is most common to use single line comments.
Block comments are often
used for formal documentation.
Using Comments to Prevent Execution
Comments are helpful for stopping code from running, especially when you're testing it.
When you put //
before a line of code, it turns that line into a comment instead of an active piece of code.
This example uses // to prevent execution of one of the code lines:
This example uses a comment block to prevent execution of
multiple lines:
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comments</h2>
<p id="demo"></p>
<script>
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:
document.getElementById("demo").innerHTML = y;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comments</h2>
<h1 id="myH"></h1>
<p id="myP"></p>
<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>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comments</h2>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my Homepage";
document.getElementById("myP").innerHTML = "This is my first paragraph.";
*/
document.getElementById("myP").innerHTML = "The comment-block is not executed.";
</script>
</body>
</html>