How to Write Comments in JavaScript

All programming languages have the capability for the programmer to add comments into the code. Comments, unlike the other parts of the code, are intended for humans. Writing good comments are an important part of coding. Comments provide notes on what the code is doing.

Some professional programmers will say that good programming does not need explanation. But, as a beginner in coding, you should make use of comments.

Two methods to indicate a comment in JavaScript

Comments on a single line are started with two forward slashes //.

function pageTransition () {
  var tl = gsap.timeline();

  tl.set('.loading-screen', {transformOrigin: "bottom left"});
  //raises div to the top of the screen, horizontally
  tl.to('.loading-screen', { duration: .5, scaleY: 1});
  //moves div off top of screen
  tl.to('.loading-screen', { duration: .5, scaleY: 0, skewX: 0,
 transformOrigin: "top left", ease: "power1.out", delay: 1});
}

On lines 5 and 7, you can see two different single line comments. Those comments describe the code in the very next line that follows the comment.

The reason you write this type of comment would be for yourself: so that you remember a month later what the code is doing. As you are learning to code, leaving a lot of explanations is a good form of teaching yourself what the code does. Also, comments help others understand your code. As you gain more experience, you will write fewer comments.

Multi-line comments, or block comments, start with the opening tag /* and end with the closing tag */

function pageTransition () {
  var tl = gsap.timeline();

  tl.set('.loading-screen', {transformOrigin: "bottom left"});
  /*
  tl.to('.loading-screen', { duration: .5, scaleY: 1});
  tl.to('.loading-screen', { duration: .5, scaleY: 0, skewX: 0,
 transformOrigin: "top left", ease: "power1.out", delay: 1});
*/
}

The multi-line comment above comments out, or disables, those lines of code. In most code editors, lines that are comments will be grayed out and not in color. You can use comments in this manner to debug code when you are trying to troubleshoot a problem.

Cleaning up comments

When you are finished coding, either before you turn in an assignment or start using code for production work, go back and delete any unnecessary comments. This will make your code more readable in the long-term.


Posted

in

by