JS Comments

The JavaScript (and any other programming language) are used to explain the code,warnings or suggestions and make the program more readable for developers.

Comments can also be used to prevent the execution of certain code lines. This is useful when testing;

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

  • Single-line comments (which comments out one line or a part of one line)
  • Multi-line comments (which comments out a block of code);

 

The commentary on a part or a full line of JavaScript code is done using single line comments. We can use it for either - explaining the code or debugging (commenting out to prevent execution of the browser).

It is represented by double forward slashes (//). It can be used before and after the declaration.

For Example:

<script>
// It is single line comment or Inline comment 
document.write("Hello! UK Academe"); 
</script>

Output:

 

This example uses a single line comment at the end of each line to explain the code:

For Example:

<script>
var x = "Hello!"; // Declare x, give it the Text of Hello!
var y = x +" UK Academe"; // Declare y, give it the Text of UK x + Academe 
// Write y to demo:
document.getElementById("demo").innerHTML = y;
</script>

Output:

 

Multi-line JavaScript comments are the same in purpose as single-line comments. However, the syntax varies a little. Multi-line comments in JavaScript start with a symbol: /* and when the comment ends, we use the symbol: */.

JavaScript will ignore any text between / * and * /.

For Example:

<script>
/* It is multi line comment.
It will not be displayed */
document.write("Example of javascript multiline comment");
</script>

Output:

 

Note: It is most common to use single line comments. Block comments are often used for formal documentation.