JS Comments

JavaScript comments are used to write messages that explain the code. Comments are useful to display information about the code this information is useful for everyone who will read the code. We can display warnings, instructions about the code by using comments.

The browser ignores the comments when executing JavaScript code.

Advantages of Comments

  • Comments are useful to display information about the code this makes the code easy to understand for the user. We can use comments to write brief description about the code.
  • We can avoid unnecessary code that we use for temporary purpose. Very often we write code that is for temporary purpose we do not need that in actual execution but we implement temporary logic. In such scenario we can comment that code to skip it from actual execution.

Types of Comments in Javascript


There are two ways of writing comments in JavaScript.

  • Single Line Comments
  • Multiline Comments

Single Line Comments

We can write single line comments using double forward slashes (//). We just need to add (//) before or after the code statement. The code line with (//) will be skipped by JavaScript engine during code execution. See below example.

   <script>
   //This is single line comment.
   alert("JS Single Line Comment"); // Alerts a message.
   </script>

Multiline Line Comments

We can write multi line comments using forward slash with asterisk at the start and asterisk with forward slash at the end.

We can also write single line comment using syntax of multiline comment. See below example.

   

   <script>

   /* This is single Line comment */
   /* This is a multiline 
      comment to explain the code */

   </script>

We can write comments anywhere in the JavaScript code using above mentioned syntax. The JavaScript engine ignores commented part during the code execution.

About the Author: allcodebuzz

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *