Comments - JavaScript Basics
Tags: javascript, beginners
Published: 2022-06-16 03:59:11

## How to make comments:

### Single Line Comments

In order to make single line comments,
you need to start the comment with two forward slashes, like so --> `//`.
Examples:
```js
// I am a comment
```
```js
const test = 'hi'; // I can make comments like this too. 
```
- *This second example shows that a full line is not required to make a comment*

*Note:* You can technically use the multi line comment syntax (shown below) to make a single line comment.
```js
/* I am comment */
```


### Multi Line Comments

You can also break comments out into multiple consecutive lines for larger comments.
Examples:
```js
/*
  I am a comment
*/
```
```js
/* I am
a
comment */
```
```js
/*
  I am a comment
  I am a comment
  I am a comment
  I am a comment
  I am a comment
  I am a comment
*/
```

## Why make comments:

Comments are used to make sense out of code you have wrote.

However, you should avoid commenting about everything. You don't need to. You should only use comments to explain very unclear pieces of your code or a high level understanding of the purpose of a complex function, object, class, or anything else that just looks daunting at first glance and may need clarification.

You should write code that is readable without comments. The code should explain itself. However, this is not always going to be the case.

### Examples of good reasons for comments (open for criticism for the "good reason" comment examples):
- Snippet from a Tone.js demo I created
```js
  // Reusable method for events to play the "Close Encounters of the Third Kind" Human communication to the aliens.
  closeEncountersHumans() {
    const synth2 = new Tone.Synth().toDestination();
    synth2.volume.value = -3;
    const now = Tone.now();
    synth2.triggerAttackRelease('G4', '8n', now);
    synth2.triggerAttackRelease('A4', '8n', now + 0.5);
    synth2.triggerAttackRelease('F4', '8n', now + 1);
    synth2.triggerAttackRelease('F3', '8n', now + 1.5);
    synth2.triggerAttackRelease('C4', '8n', now + 2);
  }
- This is a short sweet overview of a Class method I created for a React App. You don't need to go understand how it creates the object to create sound, you don't need to explain why the volume is the way it is, and you don't need to go an interpret the rest of this. The variable name tries to explain it, but a comment might do this method more justice. Because its purpose and output may not be completely understandable and maybe somebody just needs a sound effect for a button click. They look around the app and stumble upon this method that can produce the `"Close Encounters of the Third Kind" Human communication to the aliens` sound effect on a button click. Easy peezy. Nothing crazy.
```
- Old server code I made for a school project (incomplete router (lots missing), but a great example for this occassion):
```js
/* Purpose:
This router handles the app's request routing and error
handling for Preflight OPTIONS, GET requests for the app's
background image default background or latest uploaded
background, GET requests for remote commands to client
application, and POST requests for client application 
commands from the client application itself.
*/
module.exports.router = (req, res, next = ()=>{}) => {
  if (req.method === 'OPTIONS') {
    res.writeHead(200, headers);
    res.end();
  }
  if (req.method === 'GET') {
    if (req.url === '/') {
      const result = messageQueue.dequeue();
      res.writeHead(200, headers);
      res.write(result);
      res.end();
    }
    if (req.url === '/background.jpg') {
      fs.readFile(module.exports.backgroundImageFile, (err, fileData) => {
        if (err) {
          res.writeHead(404);
        } else {
          res.writeHead(200);
          res.write(fileData, 'binary');
        }
        res.end();
      });
    }
  }
  if (req.method === 'POST') {
    res.writeHead(200, headers);
    res.end();
  }
  next();
};
```
- There is a lot going on in this router. A good high level overview for all the possible requests that it handles will help a developer who may pick this up. Especially for a situation like this where as previous mentioned, this router was incomplete. It may be really nice for a developer on your team to quickly see in a couple of lines what this router is doing versus interpreting 20+ lines of code. Just so they can get a gauge of the "why" of each conditional checking the request url and what happens in each conditional block.

### Examples of bad reasons for comments:
```js
const something = 'Hello World'; // I made this variable so our company's code can have a "Hello World" string.
```
- You don't need to explain a variable for some primitive data type like a String type value. The use case for it should make sense wherever it is going to be used.
```js
const aFunction = () => {
  const multipliedByTwo = arguments[0].map((value) => {
    return value * 2;
  });
  return multipliedByTwo;
}; // This function iterates through the given array and returns a new array of values multiplied by two from the input array.
```
- You may be thinking, "Why shouldn't I make a comment for this, it seems very complicated?". At first, learning any new language is complicated. But think about this: You wouldn't need to tell people the reason for eating an apple. You're eating an apple at the most highest level to gain nourishment.
- Code will like this will make sense throughout your learning. And it will make sense to others too. The `map` method used here is a very common method used for iterating through an array to return another array with some manipulated values. It also can be used just to iterate through an array.
- As you learn and grow, just like learning whatever language(s) you have learned, you will gain intuition for when you should and should not use comments.