DEV Community

Max Lockwood
Max Lockwood

Posted on • Updated on • Originally published at maxlockwood.dev

How to Comment Code in JavaScript – Best Practices

Have you ever built a JavaScript programme only to discover six months later that you have no idea what’s going on in the code? You most likely failed to do something that all programmers forget to do: write comments!

When writing code, you may encounter some complex logic that is difficult to understand; this is an excellent time to add comments to the code that describe what is happening. Not only will this help you remember it later, but it will also help others comprehend it when they look at your code.

A computer programme is a set of “instructions” that a computer will “execute.” These computer instructions are known as statements in JavaScript programming language. However, not all JavaScript statements are “executed”.

Code after a double slash //, or between /* and */, is treated as a comment. Comments are ignored, and are not executed.

Single line comments

In JavaScript, you can make a single line comment by putting two slashes “//” in front of the code, which JavaScript will disregard.

It is most common to use single line comments in your code.

Here is an example:

<script>
// This is a single line comment
alert(This is an alert box!);
</script>
Enter fullscreen mode Exit fullscreen mode

Multiple-Line Comments

Comments that span multiple lines begin with /* and conclude with */. JavaScript will ignore any text between /* and */.

Here is an example:

<script>
/* This code creates a Javascript popup alert box. 
An alert box is often used if you want to make sure
information comes through to the user.
 */
alert(This is an alert box!);
</script>
Enter fullscreen mode Exit fullscreen mode

Javascript comments show what the code performs and the decisions that go into code design. They can also inhibit code execution if necessary. Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively.

To learn more about JavaScript why not check out my blog

Top comments (0)