JavaScript Comments

Javascript comments can be used to make the code more readable and more explained. Javascript offers single line comment as well as multi line comments. Comments in Javascript are ignored by the JavaScript Engine and are not executed at all.

Single line comment –

If we write any line starting with two forward slashes (//) then that particular line would become a comment.

Note : Sometimes we prevent execution of a certain part of our code by making it a comment while testing the code.

Example of a single line comment

The line we have written after // is to explain the use of document.write().

var num = 4;
//The above line would print 4

Preventing execution of code by making it a comment.

Since comments are not executed by the JavaScript interpreter, we can prevent execution of a part of code by making it a comment.

var num = 4;
//This line would print 4

The above example would print nothing, as we have commented the line document.write(num).

Multi line comments

A multi line comment can be written by starting anything with /* and ending it with */.

Example of a multi line comment:

/*The code written below 
will create a variable
named x, assign it a
value of 7, and print it.*/
var x = 4;

Preventing a bunch of lines of code by multi line comments:

var x = 4;

In above example, the value of the variable would be displayed, but the messages “Hello” and “Welcome” would
not, because we have commented them.

Note : Comments can be written anywhere, but it is a good practice to write a comment before a particular code.

Advantages of Comments in JavaScript

  • A comment in JavaScript primarily is used to explain the code to a person who is reading the code. For example if you have written some code and you pass it to your friend, then explanatory comments  would help your friend to understand the code more better.
  • At times you might need to temporarily avoid some part of our code, for that you can simply make that part a comment.