JavaScript Comments

JavaScript comments are used to deliver messages. It is used to add information about the code, warnings, or suggestions so that end-user can easily interpret the code. Comments are annotations in the source code of a program that are ignored by the interpreter, and therefore have no effect on the actual output of the code. Comments can be immensely helpful in explaining the intent of what your code is or should be doing.

JavaScript Comments – Single Line

Single-line comments are written with two forward slashes (//). All characters immediately following the // syntax until the end of the line will be ignored by JavaScript.

<!DOCTYPE html>
<html>
<body>

<script>
// This is a comment
document.write("JS Comments");
</script>

</body>
</html>

Output:

image 131

Multiline comments

 Multi-line comments are long-form annotations used to introduce and explain a section of code. Often these types of comments are placed at the top of a file, or before a particularly complex code block.

<!DOCTYPE html>
<html>
<body>

<script>
/*
The code below will 
print
two messages
*/
document.write("<h2> JavaScript Comments </h2><br>");
document.write("Hello world");
</script>

</body>
</html>

Output:

JS Comments

JavaScript commenting out code for testing

Comments can also be used to quickly and easily prevent the execution of code for testing and debugging purposes. This is referred to as “commenting out code”.

If there is an error in some code you’ve written, commenting out sections will prevent them from running, and can be helpful in pinpointing the source of the issue. You may also use it to toggle between codes to test different results. Both single-line comments and block comments can be used to comment out code, depending on the size of the section being toggled.

<!DOCTYPE html>
<html>
<body>

<h3>JavaScript Comments</h3>
<script>
/*
document.write("Welcome to my Homepage");
document.write("Hello world.");
*/
document.write("The comment-block is not executed.");
</script>


</body>
</html>

Output:

JS Comments