How to write comments in JavaScript?
Answer: Using "//"
and "/* */"
sign.
Comments in JavaScript are the piece of text, description, or code that is ignored by the JavaScript compiler at the time of program execution. The comments are used to provide additional information such as descriptions, suggestions, etc. so that users can easily understand the code. Apart from suggestions and descriptions, we can also comment the JavaScript code that we do not want to be executed by the JavaScript compiler.
There are two types of comments in JavaScript
- Single-line comment
- Multi-line comment
Single-line comments
The single-line comment in JavaScript is used to comment a single line. With the help of a single-line comment, we can either comment the explanation or a piece of code that we do not want to execute.
It is represented by the double slash (//
). There is no need to close single-line comments, and it ends when the line ends. We just have to add //
just before the text or code which we want to comment. The compiler will not execute the commented part.
Syntax
// text or code
We can also use the shortcut CTRL + / to add a single-line comment in JavaScript code, and this shortcut is supported by most modern editors such as sublime, atom, etc.
Example: Create single line comment
In the given example, we have used the double slash to comment the single line in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Comments in JavaScript</title>
</head>
<script>
//This is a single line comment
var x = 10; // declared a variable x and assigned its value 10
console.log(x);
</script>
</body>
</html>
Output
10
Multi-line comment
The multi-line comment in JavaScript is used to comment multiple lines such as a lock of code or a very long description which is 2-3 lines long or more at once. The multi-line comment starts with the /*
and ends with the */
symbol.
We can also comment single line using multi-line comments.
Syntax
/* text or code */ or
/* text
or
code */
Example: Creating multi-line comment
In the given example, we have used the /* to comment the multi-line in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Comments in JavaScript</title>
</head>
<script>
/*This is a
multi line
comment*/
var x = 10; /* declared a
variable x
and assigned
its value 10*/
console.log(x);
</script>
</body>
</html>
Output
10
Conclusion
In this lesson, we have discussed how to add comments in JavaScript. There are two methods to add comments in JavaScript. The first one is using double slash (//
), we can comment single line code or text using the double slash, and it is also known as the single-line comment. Another way is using /*
and */
. We can comment multiple lines at once using /* and */, and it is also known as the multi-line comment.