How to add comment in JavaScript

Comments are an important part of the program it allows to add notes and explanations with the code. It has no impact on the execution of JavaScript code because they are ignored when the code is run.

In JavaScript, there are two types of comments –

  • Single line, and
  • Multiple lines

How to add comment in JavaScript


Contents

  1. Single Line
  2. Multiple Lines
  3. Conclusion

1. Single Line

Use // for single line comments. If you want to comment more than one line using this then you need to add this on each line.

Syntax

<script type="text/javascript"> 

// This is a single line comment 

</script>

Example –

Create addNumbers() function to sum to numbers. Stored integer values in the num1 and num2 variables. Called addNumbers() function to sum num1 and num2.

<script type="text/javascript">

// Function to add 2 numbers
function addNumbers(num1,num1){
     return num1+num2;
}

var num1 = 10; // Number 1
var num2 = 8; // Number 2

var sum = addNumbers(num,num2);// Sum numbers

</script>

2. Multiple Lines

It starts with /* and ends with */. Between this the content that needs to be the comment.

Syntax

<script type="text/javascript"> 

/* 
This is a multi-line comment block 
*/

</script>

Example –

Using the same above example and add multiple line comment.

<script type="text/javascript">

/* 
Function to add 2 numbers
Takes 2 parameters of Number type 
*/
function addNumbers(num1,num1){
     return num1+num2;
}

var num1 = 10; /* Number 1 */
var num2 = 8; /* Number 2 */

/* Sum num1 and num2 */
var sum = addNumbers(num,num2);

</script>

3. Conclusion

The readability and maintainability of your code can be greatly enhanced by adding comments, which is a simple process in JavaScript. By using it effectively, you can make your code more understandable to other developers and ensure its longevity.

You can also use it to temporarily ignore the logic or a block of code for later use.

If you found this tutorial helpful then don't forget to share.

Leave a Comment