- JavaScript in Action
- Objects, Methods, ... and Even Properties
- Using the alert() Method
- Adding Comments to JavaScript
- Using the confirm() Method
- Using the prompt() Method
Adding Comments to JavaScript
Professional JavaScripters strive to make it easy to reread their code when they come back to it (maybe many months later). One of the things they use to help them is the JavaScript comment tags, one of which you've already come across in the previous chapterthe single-line comment.
Single-Line Comments
Here is an example of single-line comment tags in action:
<html> <head> <title>A Simple Page</title> <script language="JavaScript"> <!-- Cloaking device on! // The first alert is below alert("An alert triggered by JavaScript!"); // Here is the second alert alert("A second message appears!"); // Cloaking device off --> </script> </head> <body> </body> </html>
If you run this JavaScript, you won't notice any difference at all. That is because the comment tags have done their job and hidden the comments from the browser's view.
Multi-Line Comments
Sometimes you need to add multiple-line comments to your scripts, and although you could go round placing slashes (//) at the beginning of each line, it isn't really convenient. This is where the multi-line comment tags come into their own.
Multi-line comment tags consist of the open comment tag (/*) and then the comments themselves followed by the closing comment tag (*/).
Here is an example of a multi-line comment:
<html> <head> <title>A Simple Page</title> <script language="JavaScript"> <!-- Cloaking device on! /* Below two alert() methods are used to fire up two message boxes - note how the second one fires after the OK button on the first has been clicked */ alert("An alert triggered by JavaScript!"); alert("A second message appears!"); // Cloaking device off --> </script> </head> <body> </body> </html>
Adding meaningful comments to a script is something that only comes with practice. At first, it might seem tedious or even unnecessary, but not only does it make your JavaScripts easier to understand, in the early stages it helps you get a clearer idea of how your scripts work. Take every opportunity possible to comment your scripts!
Exercise - For the example you created for the previous exercise, comment your code using single-line and multi-line comments.