Comments in JavaScript

Comments in code are an integral part readable code which can describe what a particular piece of code is supposed to do. However, these should only give a brief but to the point information about the functionality not entire essays as that will make the code full of comments.

blog
by Jibran Advani
Published on:
3 August 2021
Last updated:
3 August 2021

It is very important to have comments in the code as these are suppose to give a brief but specific information to the reader of the code about what the code is supposed to do. JavaScript offers both multi-line and single-line comments.

A comment in code is simply the information that is ignored by the browsers while executing the code. In JavaScript, one can write some code and then comment them out so that piece of code could be ignored by browsers.

With that said, let's have a look at some of the common forms of comments in JavaScript.

Single-line comments

Below is the example of a single-line comment which just gives a brief information about what the below code is supposed to do.

1// print name to console
2console.log('John Doe');
3

Multi-line comments

Below is the example of a multi-line comment which just gives a brief information about what the below code is supposed to do.

1/* 
2  print name to console
3  print age to console
4*/
5console.log('Joh Doe');
6console.log(28);
7

Ignoring statements

Below is the example of a comment which is just written, may be, for the purpose of testing during development but was intended to get ignored while final code runs.

1console.log('Joh Doe');
2// console.log(28);
3

Comments in front of statements

Below is the example of a comment which is just written to explain the us of a particular statement.

1console.log('Joh Doe'); // Print name to console
2

Conclusion

The key take away from this article are as follows:

  • Comments are used improve code readability
  • Comments should be concise and to the point
  • JavaScript offers both multi-line and single-line comments.