πŸ“ What You’ll Learn

In this article, you’ll discover:

  • What comments are in JavaScript
  • Why and when to use them
  • The difference between single-line and multi-line comments
  • Best practices for writing useful comments

🧠 What Are Comments?

Comments are lines in your code that are ignored by JavaScript. They are used to:

  • Explain what the code does
  • Leave notes for yourself or other developers
  • Temporarily disable code for testing

They do not affect how the program runs.

πŸ“ Single-Line Comments

Use // to write a comment on one line:

// This is a single-line comment
let x = 5; // This comment is after a statement

You can also place it after a line of code for a quick explanation.

πŸ“„ Multi-Line Comments

Use /* */ to write comments over multiple lines:

/*
  This is a multi-line comment.
  It can span multiple lines.
  Helpful for longer explanations.
*/
let y = 10;

This is great when you need to describe a block of code or leave more detailed notes.

πŸ›  Commenting Out Code

Comments can also be used to temporarily disable code during development:

// let result = x + y;

This is useful for debugging or testing without deleting code.

βœ… Best Practices

  • Be clear and concise
  • Don’t state the obvious (e.g., // Add 1 to i next to i++)
  • Keep comments up-to-date as your code changes
  • Use them to explain why, not just what

⚠️ Common Mistakes

  • Over-commenting simple code
  • Leaving outdated or misleading comments
  • Forgetting to remove debug comments before going live

πŸ“˜ Recap

  • Use // for short, single-line comments
  • Use /* */ for longer explanations
  • Comment your code to improve readability and maintainability
  • Avoid clutter and keep comments relevant