Single-Line Comments in JavaScript

Question
How should single-line comments be used in JavaScript?

Answer
Here are some ways to use single-line comments:
-Place them on their own line before a line of code.
-Place them at the end of a line of code.
-Place them at the beginning of a line of code to comment it out.

Comments
Don’t use single-line comments on consecutive lines unless you’re commenting out code. Instead, favor multi-line comments for those that span more than one consecutive line.

Examples

// Good.
if (someCondition) {

  // If you are here, then you are authorized.
  grantAccess();
}

// Bad. No empty line preceding the comment.
if (someCondition) {
  // If you are here, then you are authorized.
  grantAccess();
}

// Bad. Incorrect indentation.
if (someCondition) {
// If you are here, then you are authorized.
  grantAccess();
}

// Good use of a trailing comment.
let answer = oneNumber + anotherNumber;  // answer can't be null.

// Bad. Insufficient space between the code and the comment.
let answer = oneNumber + anotherNumber;// answer can't be null.

// Solid way to comment out code.
// if (condition) {
//   doSomething();
//   thenDoSomethingElse();
// }

// Bad. A multi-line comment should be used.
// The following code is difficult to understand.
// ...
// ...
// ...
// ...
// So that's why it's implemented this way.
if (someCondition) {
  // If you are here, then you are authorized.
  grantAccess();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s