Putting Comments in Scripts

It's a good idea to get into the habit of adding comments to your scripts. You do this by inserting comments that JavaScript won't interpret as script commands. While your script may seem perfectly clear to you when you write it, if you come back to it a couple of months later it may seem as clear as mud. Comments help to explain why you solved the problem in a particular way. Another reason to comment your script is to help other people who may want to re-use and modify your script.

Script 2.4 shows examples of two kinds of script comments. The first kind is for longer, multi-line comments. The second example shows how to do single-line comments.

Script 2.4. Here's how you can annotate your script with comments, which helps you and others understand your code.

/*This is an example of a long JavaScript comment. Note the characters at the beginning
and ending of the comment.This script adds the words "Hello, world!" into the body area of the HTML page.*/window.onload = writeMessage;// Do this when page finishes loadingfunction writeMessage() {// Here's where the actual work gets donedocument.getElementById("helloMessage"). innerHTML = "Hello, world!";}

Note that we haven't included the HTML for this example, as it is the same as Script 2.2. From now on in the book, when the HTML hasn't changed from a previous example, we won't be printing it again.

And here's the script again, as in the previous example, with single-line comments. As you can see here, single-line comments can be on a line by themselves, or they can follow a line of code. You can't have a line of code on the same line after a single-line comment, nor can you have a multi-line comment on the same line as code.

Yes, we're as tired of seeing this one as you are, but it's traditional for all code books to start off with the "Hello, world!" example.