Javascript Comments
JavaScript comments are statements in your code that are not executed by the JavaScript engine, but are instead used to add information about your code for humans reading the code.
There are two types of comments in JavaScript:
Single-line comments:
Single-line comments start with two forward slashes (//
) and continue until the end of the line.
As an example:
// This is a single-line comment
Multi-line comments
Multi-line comments start with / and end with /. They can span across multiple lines.
As an example:
/*
This is a multi-line comment
It can span across multiple lines
*/
Comments clarify code, help in code maintenance & help others understand it. It is always a good practice to use them.
Uses of comments
Commenting out code
Comments can also be used to prevent execution of code. This is useful when you want to debug your code by preventing a part of the code from executing.
As an example:
function add(a, b) {
// return a + b;
}
In the above example:
- The function
add()
will not return anything.
Code documentation
Comments can also be used to generate documentation for your code. This is useful when you are writing a library or a framework.
As an example:
/**
* This function adds two numbers.
* @param {number} a - The first number
* @param {number} b - The second number
* @returns {number} The sum of the two numbers
*/
function add(a, b) {
return a + b;
}
In the above example:
- The function
add()
will return the sum of the two numbers passed to it. - The
@param
tag is used to document the parameters of the function. - The
@returns
tag is used to document the return value of the function.
Comment best practices
Commenting for readability
Comments should be used to explain the code. They should not be used to explain what the code does. The code should be self-explanatory.
As an example:
// This function adds two numbers
function add(a, b) {
return a + b;
}
In the above example:
- The comment is not required as the function name
add()
is self-explanatory.
Commenting for future reference
Comments can be used to add notes and explanations for future reference.
As an example:
// This function adds two numbers
function add(a, b) {
return a + b;
}
// This function subtracts two numbers
function subtract(a, b) {
return a - b;
}
In the above example:
- The comments are not required as the function names
add()
andsubtract()
are self-explanatory.