How to Comment in JavaScript: Syntax and Examples
In JavaScript, you can add comments using
// for single-line comments and /* */ for multi-line comments. Comments are ignored by the browser and help explain your code.Syntax
JavaScript supports two types of comments:
- Single-line comment: Starts with
//and continues to the end of the line. - Multi-line comment: Starts with
/*and ends with*/, spanning multiple lines if needed.
javascript
// This is a single-line comment /* This is a multi-line comment that spans multiple lines */
Example
This example shows both single-line and multi-line comments in action. Comments do not affect the program output.
javascript
// Single-line comment console.log('Hello, world!'); /* This prints a greeting */
Output
Hello, world!
Common Pitfalls
Common mistakes include forgetting to close multi-line comments or trying to nest comments, which JavaScript does not support.
Also, placing code inside comments will prevent it from running.
javascript
/* This is a multi-line comment console.log('This will not run'); // Missing closing */ // Wrong: Nested comments /* Outer comment /* Inner comment */ Outer continues */ // Correct usage: /* Outer comment Inner comment is not allowed, so just write plain text */
Quick Reference
| Comment Type | Syntax | Use Case |
|---|---|---|
| Single-line | // comment text | Short notes or explanations on one line |
| Multi-line | /* comment text */ | Longer explanations or disabling blocks of code |
Key Takeaways
Use // for single-line comments and /* */ for multi-line comments in JavaScript.
Comments help explain code and are ignored when the program runs.
Never nest multi-line comments; JavaScript does not support this.
Always close multi-line comments properly to avoid syntax errors.