In JavaScript, there are two types of comments: **single-line comments** and **multi-line comments**. Here are explanations and examples for each:
### 1. Single-line Comments
To write a single-line comment, use `//` at the beginning of the line. Anything after `//` on that line will be ignored by JavaScript.
```javascript
// This is a single-line comment
let greeting = "Hello, JavaScript"; // This comment is after a line of code
```
### 2. Multi-line Comments
To write a comment that spans multiple lines, start with `/*` and end with `*/`. Everything between `/*` and `*/` will be ignored by JavaScript.
```javascript
/*
This is a multi-line comment.
It can span multiple lines, which makes it useful for longer explanations or documentation.
*/
let message = "Hello, JavaScript";
```
### Example: Using Both Types of Comments Together
```javascript
// Declaring a variable to store the greeting message
let greeting = "Hello, JavaScript";
/*
Displaying the message in the browser
This approach can be used to create simple tutorials
*/
document.write(greeting);
```
### Tips for Commenting Code
- **Single-line comments** are best for brief notes or explanations on specific lines of code.
- **Multi-line comments** are useful for more detailed explanations, outlining complex logic, or providing documentation.
- **Write comments to clarify** the *why* of the code, not just the *what* – explain intent and logic rather than restating code structure.
Comments improve code readability and help others (and your future self!) understand the code more easily.