JavaScript comments

The JavaScript from the input page contained this line:

// Get the user's name and say hello.

This is a comment in the JavaScript program. The page already has an HTML comment marked by <!-- ... --> but the double forward slash marks the start of a JavaScript comment to explain what's happening in the program itself.

There are two types of comment in JavaScript. One type starts with a double slash and everything that follows until the end of the line will become a comment. The other type starts with /* and everything that follows until */ will become a comment. This second style is very useful because it can extend over several lines and you can use it to temporarily remove a section of code from your program. Put a /* at the start and a */ at the end and that whole section of code will be ignored.

Writing comments

Use the first type of comment for the usual purpose of explaining what the program is doing. To be more precise, use them to explain why the program is doing what it's doing.

There is no use at all in a comment like this:

// Use prompt to display "What is your name"
// Set the default name to be blank
userName = prompt("What is your name", "");

Anyone reading the program can see that you're using prompt to display this text and that the default will be blank. What they need to know is why you're doing it. This next sample would have been a more useful comment. It's shorter but it tells the reader something that they can't see from the code itself.

// We need the user name to personalise the output
userName = prompt("What is your name", "");

Debugging with comments

If you get into the habit of using // for your regular programming comments then you can use the other style as an aid to debugging.

You should always write programs in short bursts, testing as you go, and you will often find that the last bit you've added has stopped the program working. Sometimes the Error Console will tell you where you've made the mistake. Sometimes it won't.

What you do in these circumstances is to wrap that latest section of code in a pair of /* ... */ comments so that the browser just sees the original code. The page should now go back to working as it did a few minutes ago. You then expose bits of the new code by moving the comment symbols. Eventually you'll expose the block of lines which cause the program to fail again and you can concentrate your debugging on that section.

MS Access technical tips

Visual FoxPro technical tips

General Tips

 

More tips from Alvechurch Data

Search page for Alvechurch Data

Searching a web site with JavaScript

Read More

Site Map

Site map of the Alvechurch Data site

Read More

Javascript while loops

JavaScript do and while loops

Read More

Javascript for loops

Javascript for loops

Read More

Repetition in Javascript

JavaScript structures for repetition

Read More