Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between single-line and multi-line comments in JavaScript?
JavaScript supports two types of comments: single-line comments using // and multi-line comments using /* */. Comments help document code and are ignored during execution.
Single-Line Comments
Single-line comments start with // and continue until the end of the line. Everything after // on that line is treated as a comment.
Syntax
// This is a single-line comment
Example
// This is a comment explaining the variable let userName = "John Doe"; let age = 25; // Age of the user console.log(userName); // Output the user's name console.log(age);
John Doe 25
Multi-Line Comments
Multi-line comments start with /* and end with */. They can span multiple lines and are useful for longer explanations or temporarily disabling code blocks.
Syntax
/* This is a multi-line comment that spans several lines */
Example
/*
This function calculates the area of a rectangle
Parameters: length and width
Returns: area as a number
*/
function calculateArea(length, width) {
return length * width;
}
let area = calculateArea(5, 3);
console.log("Area:", area);
/*
The following code is temporarily disabled
let oldVariable = "not needed";
console.log(oldVariable);
*/
Area: 15
Comparison
| Feature | Single-line (//) | Multi-line (/* */) |
|---|---|---|
| Syntax | // comment |
/* comment */ |
| Span multiple lines | No | Yes |
| Best for | Quick explanations | Long descriptions, disabling code |
Nested Comments
Multi-line comments cannot be nested. If you try to nest /* */ comments, the first */ will close the comment.
/*
This is the outer comment
/* This inner comment will cause problems */
This text will not be commented out!
*/
console.log("This might cause an error");
Conclusion
Use single-line comments for brief explanations and multi-line comments for longer documentation or temporarily disabling code blocks. Both are essential tools for writing maintainable JavaScript code.
