JavaScript Block Comments

September 30, 2009

I ran across an interesting little tidbit in a JavaScript book, I think, or online. Likely I saw it in something Douglas Crockford wrote, but couldn’t be certain. Anyway, it has to do with comments in JavaScript. The language supports two comment types:

1. Single line using the double slash:

// This is a comment.

2. Multiline (also called block) using the slash-asterisk combination:

/* This comment
can go over multiple
lines. */

The argument made (wherever it was made) is that you shouldn’t use the multiline comment style as the */ character combination can appear in JavaScript code. Namely, it might appear in a regular expression match, when slashes are used to delineate the pattern and the asterisk is a pattern modifier that looks for zero or more of something. A syntax error will arise if you use block comments around some code that includes a problematic regular expression:

/* some code
var x = 'some string'.search(/[a-z]*/g);
some code */

That’s obviously a useless example in itself, but it shows a situation in which a problem is caused by using block comments.

All that being said, I wouldn’t suggest that you avoid using multiline comments. They’re quite handy, both for adding lots of documentation and for debugging purposes (by making blocks of code inert). But the potential conflict is something to be aware of, particularly when you apply multiline comments to render some code non-executing and all of a sudden have a syntax problem.