1. Computing & Technology

JavaScript By Example

5. Comments

From , former About.com Guide

There are two ways that you can enter comments into your JavaScript. The first way which produces multi-line comments is to wrap the comment inside /* */ where you can then have anything at all inside the comment except for */ and the second way which produces single line comments is to start the comment with // where the comment will then include the rest of the current line and can include anything at all in the comment.

You can make your multi-line comments stand out from the surrounding code by creating a decorative box around the text as I have shown in this example. Such comments are useful for the copyright notice and script description that you should place at the top of the script as well as for a description of what sections of your code do where the code itself doesn't make it obvious (you should try to make your code as self documenting as possible to reduce the need for comments). Multi-line comments can also be used to comment out sections of your code during testing to allow you to test it a piece at a time.

Single line comments can either be on a line by themselves or can be on the end of a line after a statement. One use for single line comments is to document the valid ranges for values that are assigned at the top of your script that will be substituted within the script. While these will normally be a fixed value for a particular copy of the script you may decide to use the script elsewhere with different values.

These suggestions of where to use the comments will make more sense as you learn more JavaScript. At the moment the important thing is to learn how to write comments.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 05</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="example05.js"></script>
</body>
</html>

JavaScript


/* **************************************** *
 * My Fifth Example Script                  *
 * copyright: your name                     *
 * **************************************** */

var hello =
'hello world'; // in line comment
document.getElementById('ex').innerHTML = hello;
/* end of script */

©2012 About.com. All rights reserved.

A part of The New York Times Company.