JavaScript Comments
Learn how to write comments in JavaScript, understand the different types of comments, and discover best practices for writing clean and maintainable code.
Reading Time
8 min
Lesson
Lesson 3 of 48
What are Comments?
Comments are lines of text that are ignored by the JavaScript engine. They are written to explain code, improve readability, and help developers understand the purpose of a piece of code. Comments are not executed when the program runs.
Why Use Comments?
Writing meaningful comments makes your code easier to understand and maintain. They are especially useful when working in teams or when revisiting your own code after a long time.
Benefits of Comments
- Improve code readability
- Explain complex logic
- Help during debugging
- Make collaboration easier
- Temporarily disable code
Single-line Comments
Single-line comments begin with two forward slashes (//). Everything after // on the same line is treated as a comment.
Single-line Comment Example
Console Output
Click “Run” to see the console output here.
Multi-line Comments
Multi-line comments begin with /* and end with */. They are useful when writing longer explanations or documenting multiple lines of code.
Multi-line Comment Example
Console Output
Click “Run” to see the console output here.
Commenting Out Code
During development, developers often comment out code temporarily instead of deleting it. This helps while testing different approaches.
Temporarily Disable Code
Console Output
Click “Run” to see the console output here.
Single-line vs Multi-line Comments
| Feature | Single-line (//) | Multi-line (/* */) |
|---|---|---|
| Syntax | // | /* */ |
| Lines | One Line | Multiple Lines |
| Best For | Short Notes | Long Descriptions |
Best Practices
Write comments only when they add value. Avoid explaining obvious code. Instead, explain why the code exists or why a specific approach was chosen.
Common Mistake
Do not write unnecessary comments for simple code. Poor comments can make code harder to read and maintain.
Bad vs Good Comments
Console Output
Click “Run” to see the console output here.
Summary
Comments are an essential part of writing clean code. Use single-line comments for short explanations and multi-line comments for detailed documentation. Always keep comments meaningful and up to date.