1 minute read

Comments in JavaScript improve code readability, helping developers understand, maintain, and collaborate on codebases. Although the JavaScript interpreter ignores comments, they guide human readers by explaining the functionality and purpose of code snippets. In this topic, we'll explore the types of comments supported in JavaScript and how to use them effectively.

Single-line comments

These refer to comments that only occupy one line. They are initiated with //. Here's an example:

console.log("Nice to see you!"); // This code outputs the message to the console

In the example above, the interpreter ignores the text after //. With the help of this note, you can understand what a specific code fragment is intended for, even if it's been a while since you wrote it.

Multi-line comments

These are comments that span across multiple lines and are enclosed between /* and */. For example:

/*  
  The following code outputs the message to the console
  The console will display a line with the text "Hello, JS!"
*/
console.log("Hello, JS!");

The interpreter ignores all text between /* and the nearest */. Such comments help explain complex code pieces or temporarily comment out code fragments when you need to find an error. Also, multi-line comments at the beginning of a file are pretty useful for specifying copyright information.

Sometimes, you may find a slightly modified syntax of multi-line notes: the comment opens with the /** tag, and each line starts with an *:

/**
* The first program
* Author: Bob  
*/
console.log("Hi, I'm Bob");

Such comments often contain information about the programming file, including its name, version, and the script author.

Best Practices

  • Use comments to explain the "why" behind complex code logic, not just the "what."

  • Avoid obvious comments; aim for self-explanatory code.

  • Update comments as your code evolves to avoid confusion.

  • Use comments to improve collaboration, especially in team projects.

  • JavaScript does not support nested comments. This means that you cannot write a comment inside another comment.

Conclusion

Comments clarify your code and ease the work for future developers, including yourself. Use them to document your thought process and boost collaboration. However, remember that comments cannot replace well-written, clean code.

963 learners liked this piece of theory. 5 didn't like it. What about you?
Report a typo