JavaScript comments are used to add notes or explanations within the code without affecting execution. They help make the code more readable and easier to understand.
//
)//
and applies only to that line.Example:
// This is a single-line comment
console.log("Hello, World!"); // This prints a message
/* ... */
)/*
and ends with */
.Example:
/*
This is a multi-line comment.
It can span multiple lines.
*/
console.log("Welcome to JavaScript!");
You can disable specific code lines without deleting them by commenting them out.
Example:
let x = 10;
let y = 20;
// let sum = x + y; // This line is disabled
console.log(y); // Output: 20
✔ Write meaningful comments – Explain why, not what.
✔ Avoid excessive comments – Keep it concise.
✔ Use comments to structure code – Separate sections with clear comments.
Example:
// Function to calculate the square of a number
function square(num) {
return num * num; // Returns squared value
}
JavaScript comments improve code readability, help in debugging, and organize code efficiently. Use single-line comments (//
) for short notes and multi-line comments (/* ... */
) for longer explanations.