Like many other programming languages comments in javascript serve a couple of purposes
comments can be used to explain JavaScript code, and to make it more readable. This is especially useful when multiple people will work on code.
comments can also be used to prevent execution of code, when you want to test alternative code.
Types
There are two types of comments in JavaScript.
- Single-line Comment
- Multi-line Comment
Single line Comment
A single line comment is represented by double forward slashes (//). It can be used before and after a statement.
Any text between (//) and the end of the line will be ignored by JavaScript (that is it will not be executed).
Lets see an example of each
<script> // A single line comment document.write("hello world"); </script>
Now lets see it after the statement
<script> document.write("hello world"); //single line comment </script>
Multi line Comment
This can be used to add single as well as multi line comments. It is represented by a forward slash with asterisk then asterisk with forward slash.
Any text between /*
and */
will be ignored by JavaScript and will not be executed.
This is a single liner example
/* a comment */
And now for a multi line example
<script> /* This is an example of a multi line comment */ document.write("javascript multiline comment example"); </script>