Code comments

Did you know that you can read content offline by using one of these tools? If you would like to read offline MDN content in another format, let us know by commenting on Bug 665750.

Dash App

Table of Contents

Comments are used to add hints, notes, suggestions, or warnings to JavaScript code. This can make it easier to read and understand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool.

JavaScript has two ways of assigning comments in its code.

The first way is the // comment; this makes all text following it on the same line into a comment. For example:

function comment() {
  // This is a one line JavaScript comment
  alert("Hello world!");
}
comment();

The second way is the /* */ style, which is much more flexible.

For example, you can use it on a single line:

function comment() {
  /* This is a one line JavaScript comment */
  alert("Hello world!");
}
comment();

You can also make multiple-line comments, like this:

function comment() {
  /* This comment spans multiple lines. Notice
     that we don't need to end the comment until we're done. */
  alert("Hello world!");
}
comment();

You can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution:

function comment(x) {
  alert("Hello " + x /* insert the value of x */ + " !");
}
comment("world");

In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:

function comment() {
  /* alert("Hello world!"); */
}
comment();

In this case, the alert() call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.

Tags (2)