JavaScript Comments
When writing complex JavaScript, you will often find that you do not understand code once you have written it. To help yourself, or another developer working on the same project with you, understand it later, JavaScript developers use comments. Comments are simply human-readable blocks of text in the code, in which you can write anything you like.
Line comments
var x = 0;
// This is a line comment
do_something(); // This is another line comment
This is a simple single-line comment, the most common type of comment. A single line comment can go anywhere, and is started with a double forward slash - //.
Anything on the same line after the double slash will be ignored by
JavaScript, so you can safely put in random text, comments, even
another double slash.
Typically you will write a few comment lines for every complex section of code. You can use these comment lines to document what the code does, and how it can be modified if needed. If you have a long comment, you should split it across multiple lines - you can have as many line comments as you like.
Block comments
var x = 0;
do_something();
/* This is a block comment.
It can span multiple lines, and have
what could be valid_javascript();
You can put almost anything at all in here. */
This is an example of a block comment, or comment block. A comment block starts with a forward slash and asterisk - /* - and ends with the reverse - */. You can put any text in between the two, except, of course, another asterisk and forward slash, as this would end your comment.
Commenting out code
Another common use of comments is for commenting out code. For example, if you want JavaScript to skip over one or more lines of code, just comment it.
var x = 0;
var y = 10;
do_something();
do_something_else();
/*
this_will_not_happen();
NeitherWillThis();
if (orThis()) {
// The script will never get to this if block
// when the block comment is in place.
}
*/
In this example, we have a section of the code with the this_will_not_happen(); call, the NeitherWillThis(); call and an if
block. Within the if block is a standard line comment - remember, if
you have line comments in within your code, you can still block comment
the section and the line comments will still be ignored.
We've now covered all the main areas of JavaScript syntax. To refresh your memory, have a quick look through our JavaScript Syntax Reference.
| « JavaScript For Loop | JavaScript Syntax Reference » |

