JavaScript Comments
JavaScript comments are used to explain the purpose of the code. The comments are not executed as a part of program and these are solely meant for human developers to understand the code better.
You can use comments for various purposes, such as −
- Explaining the purpose of a particular piece of code.
- Adding documentation to your code for yourself and others who may read it.
- Temporarily disabling or "commenting out" a block of code for testing or debugging without deleting it.
A good developer always writes a comment to explain the code.
There are two common ways to write comments in JavaScript −
- Single-line comments
- Multi-line comments
Single-line comments in JavaScript
We can start the single-line comment with the double forward slash (//). We can write comment between // and end of the line.
Syntax
The syntax for the single-line comments is given below −
<script> // single-line comment message </script>
Example
In the example below, we have explained each step of JavaScript code using single-line comments. In the output, the code prints the concatenated string.
Example
In the example below, we have commented the 'bool1 = false;' line to avoid execution of that code. In the output, we can see that value of the bool1 variable is true, as we commented out the code, which updates the bool1 variable’s value.
Also, we can add the single line code after writing the code, as we added after the document.write() method.
Multi-line comments in JavaScript
The multi-line comment is useful when we require to comment the multiple lines of code or explain the larger codes. We can write multi-line comments between the /* and */.
Syntax
The syntax for the multi-line comments is given below −
<script> /* First line of comment message The second line of the comment message */ </script>
Example
In the example below, we have defined 'a' and 'b' variables. After that, we have written the code to swap values of 'a' and 'b' in 3 lines and comment out using the multi-line comments.
The output prints the actual values of the 'a' and 'b' as the browser ignores the commented code.
Always write comments in your code as it helps other collaborators to understand your code.
No comments:
Post a Comment