Chapter 2. Comments

Comments are often the least popular part of coding. They’re dangerously close to documentation, which is the last thing any developer wants to spend time doing. However, comments are incredibly important for the overall maintainability of the code. Opening a file without any comments may seem like a fun adventure, but when there are deadlines to meet, this task turns into torture. Appropriately written comments help tell the story of code, allowing other developers to drop into a part of the story without needing to hear the beginning. Style guidelines don’t always cover commenting styles, but I consider them important enough to warrant their own section.

JavaScript supports two different types of comments: single-line and multiline.

Single-Line Comments

Single-line comments are created by using two slashes and end at the end of the line:

// Single-line comment

Many prefer to include a space after the two slashes to offset the comment text. There are three ways in which a single-line comment is used:

  • On its own line, explaining the line following the comment. The line should always be preceded by an empty line. The comment should be at the same indentation level as the following line.

  • As a trailing comment at the end of a line of code. There should be at least one indent level between the code and the comment. The comment should not go beyond the maximum line length. If it does, then move the comment above the line of code.

  • To comment out large portions of code ...

Get Maintainable JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.