Home > Articles

  • Print
  • + Share This
This chapter is from the book

Workshop: Using Comments

In Hour 2, you used HTML comments to hide your script from older browsers. JavaScript also includes its own type of comments. While these won't hide JavaScript from anyone or anything, they are useful for their intended purpose—commenting on your script.

Comments allow you to include documentation within your script. This will be useful if someone else tries to understand the script, or even if you try to understand it after a long break. To include comments in a JavaScript program, begin a line with two slashes, as in this example:

//this is a comment.

You can also begin a comment with two slashes in the middle of a line, which is useful for documenting a script. In this case, everything on the line after the slashes is treated as a comment and ignored by the browser. For example:

a = a + 1; // add one to the value of a

JavaScript also supports C-style comments, which begin with /* and end with */. These comments can extend across more than one line, as the following example demonstrates:

/*This script includes a variety
of features, including this comment. */

C-style comments are often used for commenting out sections of code. If you have some lines of JavaScript that you want to temporarily take out of the picture while you debug a script, you can add /* at the beginning of the section and */ at the end.

NOTE

Since these comments are part of JavaScript syntax, they are only valid inside <script> tags or within an external JavaScript file.

  • + Share This
  • 🔖 Save To Your Account