Commenting your JavaScript code

When your scripting code becomes large, it become necessary to use comments. With comments, you can add extra information pertaining to your code. Comments are ignored (i.e., are not processed as coding instructions) by the computer. Comments not only help you understand your code when you look after a period of time but also others who are working with you on the same coding project.

JavaScript provides two types of comments:

  1. Single-line comments. Single-line comments start anywhere in the line and continue to the end of the line. Single-line comments begin with a double forward slash (//), causing the JavaScript interpreter to ignore everything from that point to the end of line. For example,
    <script language="javascript">
    // Author: Scripting Master
    // Description: This JavaScript code prints a simple message.
    document.write ("Learn JavaScript by examples."); // prints a message
    </script>
  2. Multiline comments. Multiline comments span multiple lines. Multiline comments start with slash-asterisk (/*) and end with asterisk-slash (*/) pair. For example,
    <script language="javascript">
    /* Author: Scripting Master
    Description: This JavaScript code prints a simple message.*/
    document.write ("Learn JavaScript by examples."); // prints a message
    </script>

You can add as many or few comments as you like in your JavaScript code. You do not have to comment every line but the idea is to write clear, concise, and meaningful comments to describe your code to help you or others understand what the code does.

Comments also can be used to debug (the act of finding and eliminating problems in your code) your code. By debugging with comments, you comment out lines of code that you think is causing the problem.