JavaScript comments are used to explain code and make it more readable.
They can also be used to prevent code from executing, such as when testing alternative code.
Single Line Comments
Single-line comments begin with //
.
Any text following //
until the end of the line is ignored by JavaScript and will not be executed.
In this example, a single-line comment is placed before each line of code.
<script>
// Assigning integer value to a variable x
let x = 10;
// Calculating value of the variable y
let y = x + 5;
// Write y to demo
document.getElementById("demo").innerHTML = y;
</script>
This example uses a single-line comment at the end of each line to clarify the code.
<script>
let x = 10; // Assigning integer value to a variable x
let y = x + 5; // Calculating value of the variable y
document.getElementById("demo").innerHTML = y; // Write y to demo
</script>
Multi-line Comments
Multi-line comments begin with /*
and end with */
.
Any text between /*
and */
is ignored by JavaScript.
This example uses a multi-line comment (block comment) to explain the code.
<script>
/*
The code below will update
the heading with the id "myH"
and the paragraph with the id "myP"
on my webpage:
*/
document.getElementById("myH").innerHTML = "Welcome to My Website";
document.getElementById("myP").innerHTML = "This is the introduction to my first webpage.";
</script>
Using Comments to Prevent Execution
Using comments to prevent code from executing is useful for testing.
Placing //
in front of a line of code converts it from an executable statement to a comment.
<script>
// document.getElementById("myP").innerHTML = "My first paragraph.";
document.getElementById("myP").innerHTML = "My alternate paragraph for testing.";
</script>
This example uses a comment block to disable the execution of multiple lines of code.
<script>
/*
document.getElementById("myH").innerHTML = "Welcome to My Website";
document.getElementById("myP").innerHTML = "This is the introduction to my first webpage.";
*/
</script>