How to Write a JavaScript Comment: Beginners Tutorial

When developing any sort of project, occasionally you want to write code or notes that you don’t want the computer to read. Whether this is to explain something to yourself, helps you test things, or something in-between, these sorts of additions are not only very useful, but quite common in professionally developed programs. If you haven’t guessed it yet, we’re talking aboutĀ comments. And, in this JavaScript comment tutorial, we’re going to go over just how to use comments in your programs. Whether you’re building a website or HTML5-based games, this tutorial will help you enhance how you work with your code and with JavaScript in general.

About Comments

JavaScript has two simple ways to comment code: single line ( //comment hereĀ  ) and multi-line ( /*comment here*/Ā  ). While code is for computers, comments are for people (including your future-self) and are completely ignored by the JavaScript interpreter (i.e. it has no effect on the executing code).

When you’re immersed in a section of code, it’s easy to remember the context. However, when a different developer (or your future-self) returns to existing code, it’s also easy to forget exactly what the code was intended to be doing in the context of the program as a whole. This is where code comments shine.

Single-line Comments

For single-line comments, the JavaScript interpreter ignores everything to the right of the //Ā  until the end of the line. These comments generally describe what the next line of code is doing or when located on the same line as a code statement (known as an inline comment). ThisĀ provides a succinct annotation.

Syntax for Single-line Comments

As mentioned, single-line comments use two forward slashes ( // ) to tell JavaScript to ignore all text that follows on the same line. The important thing to remember is that “comments are for people; not computers”; so just because you can write a long line of text, doesn’t mean you should. With this in mind let’s consider some Best Practices.

Best Practices for Single-line Comments

Most comments should be placed on the line above the code being documented.

// Prints "Hello World!" to the console
console.log("Hello World!");

Concise comments or annotations, especially referring to the result of a JavaScript statement, can be placed after the code it describes as long as it’s on the same line. This is generally referred to as an inline comment.
console.log("Hello World!"); // Prints "Hello World!" to the console

While technically valid, single-line comments containing a lot of text can be difficult to read and should therefore be avoided.
// I am a single line comment. Everything that follows, on this same line, is ignored by the computer. In this example, I am located above the JavaScript code I'm documenting. The code that follows prints "Hello World" to the console.
console.log("Hello World!");

While technically valid, all “inline comments” comments containing a lot of text will be difficult to read and should therefore be avoided.
console.log("Hello World!"); // I am a single line comment. Everything that follows, on this same line, is ignored by the computer. In this example, I am located on the same line as the JavaScript code I'm documenting. As long as I'm after the JavaScript code; the code will still execute. The code before me prints "Hello World" to the console.

Multi-line Comments

Syntax for Multi-line Comments

To help make comments easier to understand, JavaScript provides a second alternative. The syntax ( /* comments go here */Ā ) is a much more flexible option that allows you to optionally break your comment into multiple lines. In addition to being able to tell the computer to ignore multiple lines, the other significant difference is that instead of ignoring what follows, this syntax ignores what is in between the opening and closing forward slash-asterisk combination (/ ignored by computer */ ). This type of comment, sometimes called “block comments” can be on the same line, broken over multiple lines, or even placed in the middle of a JavaScript statement (though not a good idea). With this in mind, let’s consider some Best Practices.

Best Practices for Multi-line Comments

All multiline comments should be placed above the code being documented to improve readability.

/* I can exist as a single line */
console.log("Hello World!");

This is especially true for comments that are broken out over multiple lines.
/*
I can span multiple lines
The code that follows me prints "Hello World" to the console.
*/
console.log("Hello World!");

While technically valid using the multiline syntax ( /* */ ), “inline comments” containing a lot of text can be difficult to read (as is the theme here with inline comments) and should therefore be avoided.
console.log("Hello World!"); /* I am a single line comment. Everything that follows, on this same line, is ignored by the computer. In this example, I am located on the same line as the JavaScript code I'm documenting. As long as I'm after the JavaScript code; the code will still execute. The code before me prints "Hello World" to the console.*/

While technically valid using the multiline syntax ( /* */ ), comments should not be placed in the middle of JavaScript statements since they can become very confusing.
console.log("Hello " + /* I can be in the middle of a statement but this makes me hard to read so should be avoided unless you have a very good reason.*/ + "World!");

Development Use: Pseudocode Comments

Comments can be used as a form of pseudocode to outline intention prior to writing actual code. Pseudocode outlines the logical steps your code will take rather than the code itself.

// function to greet user
function sayHello(name) {
  // define salutation
  // define punctuation
  // create string to return
  // return result to calling function
}
/*
1. execute function
2. log result to console
*/

With your plan in place, you can now code the details.
// function to greet user
function sayHello(name) {
  // define salutation
  const returnPrefix = `Hello `;
  // define punctuation
  const returnSuffix = `!`;
  // create string to return
  const returnString = returnPrefix + name + returnSuffix;
  // return result to calling function
  return returnString;
}
/*
1. execute function
2. log result to console
*/
console.log(sayHello("Game Dev"));

Document Use: DocString Comments

DocString comments clarify what the code that follows it does. It generally includes the what, why, and sometimes who – but never the how. They also serve to document inputs, outputs, and even the name of the developer as well as many other optional, but specific, details. DocString Comments are located directly above the code block being documented and follow a format similar to multi-line comments.

Syntax for Documentation Comments

The syntax starts with /** , ends with */ , and each line within the block starts with an asterisk * . Special tagsĀ are noted within the block and start with the @ symbol such as parameters ( @param ). DocStrings identify what parameters the function expects and what it returns as well as a long list of optional details such as who wrote or modified the code last, return value and version number to name a few (https://jsdoc.app/ contains a long list of tags as well as examples).

/**
 * function says hello to user
 * @author  Cool Dev
 * @param   {String} name   - Name to greet
 * @returns {String}        - Hello message
 */
function sayHello(name) {
  return `Hello ${name}!`;
}
console.log(sayHello("Game Dev"));

Generate External Documentation

DocStrings also have added benefits including allowing you to document your code alongside the actual code itself as well as the ability to generate external documentation, in the form of an HTML webpage, based on your source code using tools such as JSDoc (https://jsdoc.app/).

Debug Use: Comment-Out

In addition to commenting your code, you can also comment-out-code. This use of the comment syntax allows you to prevent code from running without actually having to delete it. This is valuable for testing and debugging your code help to pinpoint sources of errors and isolate bugs simply by placing // in front of an executable line or surrounding a block of code with /**/ .

For example, when tracking down bugs, comment out lines potentially causing the issue. When code runs without breaking you’ve found the offending line and can investigate what’s happening.

console.log("good code");
// console.log("code with error");

You can prevent execution of a single line of code…
function sayHello(name) {
  // return `Hello ${name}!`;
  const returnPrefix = `Hello `;
  const returnSuffix = `!`;
  const returnString = returnPrefix + name + returnSuffix;
  return returnString;
}
console.log(sayHello("Game Dev"));

… or prevent execution of several lines of code.
function sayHello(name) {
  /* const returnPrefix = `Hello `;
  const returnSuffix = `!`;
  const returnString = returnPrefix + name + returnSuffix;
  return returnString; */
  return `Hello ${name}!`;
}
console.log(sayHello("Game Dev"));

Risks of Using Comments: Out-of-Date Comments

Comments are static! While code is often updated, refactored, or removed. It is very important to keep comments up-to-date with code changes.

Other developers, or your future-self, will naturally assume comments are up-to-date and valid. The consequences of these assumptions proving wrong can cause wasted time, energy, and money – worse they can introduce significant risk! Outdated comments can be worse than no comments at all so remember to maintain and update comments whenever associated code is updated or removed.

JavaScript Commenting Tips

Keyboard Shortcuts

Most code editors have a keyboard shortcut to help you quickly comment out a single line ( Ctrl + / for Windows and Cmd + / for Mac ). You can also highlight a block of code and use the keyboard shortcut to comment out all selected lines.

Best Practices

Comments are not intended to explain cryptic code. Since the code you write is generally abstracted several levels above the machine code it is eventually compiled into, you can safely use variable and function names that allow you to clearly name what you’re doing in a semi-self-documenting way.

For example, this clearly written code and the following cryptic code eventually compile to the same thing as far as the computer is concerned, so write with people and therefore clarity in mind – cleverness is generally not to be admired in code others may have to read or support.

function sayHello(name) {
  return `Hello ${name}!`;
}
console.log(sayHello("Game Dev"));

The code above and below produce the same result including the same after compile size so it’s best to choose clarity over cleverness.
function a(b) {
  return `Hello ${b}!`;
}
console.log(a("Game Dev"));

Indenting

Comments should be indented at the same level as the code immediately below them.

// function to greet user
function sayHello(name) {
  // salutation
  const returnPrefix = `Hello `;
  // end all greetings the same
  const returnSuffix = `!`;
  // create string to return
  const returnString = returnPrefix + name + returnSuffix;
  // return result to calling function
  return returnString;
}
/*
1. execute function
2. log result to console
*/
console.log(sayHello("Game Dev"));

Learning Resources

Continue your JavaScript learning with this free JavaScript 101 course for beginners, take your skills to the next level with this free Learning the JavaScript Language – COMPLETE COURSEĀ or go all-in with this premium HTML5 Game Development Mini-Degree. You might also consider trying JavaScript Tutorial Beginners by Dani Krossing or the JavaScript Tutorial For Beginners by The Net Ninja for even more JavaScript knowledge.

Happy Learning!!!

Conclusion

Through this JavaScript comment tutorial, we’ve learned a lot about how comments can help you develop your program. We first discussed the syntax of single-line ( //Ā  ), multi-line ( /**/ ), and documentation-based comments ( /** */Ā  ). We also explored how to effectively use comments for debugging, as well as the best practices and risks when using comments in general.

All this being said, remember coding comments are a great tool to use – whether it’s with JavaScript or some other programming language. Knowing how to use them properly can vastly enhance and smooth out the kinks in the development process, and just make your life that much easier. Even if it seems tedious to have to update comments, they can be worth it – especially if you can’t finish your programming in one sitting.

Best of luck on your journey to code JavaScript with confidence!!!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.