comments-in-javascript-background

Comments In JavaScript

When and why would you use them?

What are comments?
A comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.

Why would we use comments in code?
  • Explain Code
  • Test Code

Explain

JavaScript comments can be used to explain JavaScript code, and to make it more readable and understandable to other users or to yourself if you come back to your code after a long period.

Test

JavaScript comments can also be used to prevent execution of code, when testing alternative code.

comments-in-javascript
Types of comments in JavaScript:
  • Single line comment
  • Multi-line comment

Single line comment

Single line comments start with // Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

Multi-line comment

Multi-line comments start with /* and end with */ Any text between /* and */ will be ignored by JavaScript.

Conclusion

Comments in code play an important role. They help others easily understand what's going on in your code. Many would argue that good code doesn't require comments but as a beginner, it's best to keep adding comments to your code so that you develop that habit.

NOTE: Make sure you add comments only when necessary. Don't go overboard with it!

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler
Share: