They are human-readable descriptions or explanations of code that we add to our script code to make the script easier to understand and maintain.
For example, here is a comment that expresses the value used to initialize a variable “x”:
let x = 50; // Variable declaration and initialization.
- Single line comment
- Multiline comment
Let’s understand one by one with examples.
Single Line Comments
Single line comment is represented by double forward slashes (//). It can be used before and after a text. That is, placing two slashes (//) before and after the statement makes it a single line comment.
Let’s take a simple example where we will place a single line comment before a statement.
We can also write single line comment as one line as:
let x = 25; // Here, x is a variable that is initialized with a value.
Program code 1:
<DOCTYPE html> <html> <head> <title>Single Line Comment Example</title> </head> <body> <script> // Variables declaration and initialization. var x = 20; var y = 30; var z = x + y ; // It will add the values of variables. document.write("Sum: " +z); // This statement will print the sum of two numbers. </script> </body> </html>
Output of code: Sum: 50
Sometimes a single line comment is not enough for the description of script that we want to provide. In a such situation, we can multiline comment.
This is an example of multiline comment below:
Program code 2:
Output of code: Hello! I am Deepak and a Web programmer in class 10. I am in RSVM, Dhanbad
Using Comments to Prevent Execution of Code
We can also use comments to forbid execution of code is suitable for code testing. Placing a double forward slash (//) in front of a code line changes an executable code line to a comment line.
The below example uses // to prevent execution of one of the code lines:
Commenting Best Practices
Let’s point out some important points, about how to properly use comments to make our code easy to read:
1. Always comment your code as you are writing it. Writing comment may be boring for you, but it is an essential part of the code.
2. Don’t defer comment for writing later when you’re writing code. It is not a good thing.
4. Do not complicate your comment unnecessarily with the code. Be clear and concise.
5. If a line of code is self-explanatory, do not waste your time to comment about obvious code.
These are some important points that you must keep in mind for best practices.
There are many advantages of adding comments that the script code follows. They are:
2. It helps the programmers to make the script maintainable.
3. Comments also helps to hide unnecessary code. Sometimes, we add the script code to perform some function. But after sometime, function may not be necessary and need to disable the code. In such case, comments helps to hide the code by commenting the script code.
Thanks for reading!!!