Comments in JavaScript: A Beginner’s Guide
#Comments in JavaScript: A Beginner’s Guide
Comments are an essential part of writing clean, readable, and maintainable code. In JavaScript, comments are used to explain code, leave notes for future developers, or temporarily disable code during debugging.
This tutorial covers the different types of comments in JavaScript and best practices for using them.
Use //
to write a single-line comment.
// This is a single-line comment
let name = "John"; // This comment is next to a line of code
Single-line comments are often used to describe a specific line or a short block of logic.
Use /* */
to write comments that span multiple lines.
/*
This is a multi-line comment.
It can span several lines.
*/
let age = 30;
Multi-line comments are useful for explaining complex logic or sections of code.
Sometimes you may want to temporarily disable code without deleting it.
// let price = 100;
// console.log(price);
This technique is handy when debugging or testing changes.
JSDoc comments are a special form of multi-line comments used for documenting functions, classes, and APIs. They begin with /**
.
/**
* Adds two numbers.
* @param {number} a - First number
* @param {number} b - Second number
* @returns {number} Sum of a and b
*/
function add(a, b) {
return a + b;
}
JSDoc comments are especially useful in larger projects and for generating documentation.
✅ Keep comments clear and concise.
✅ Use comments to explain "why," not "what."
❌ Avoid obvious comments:
// Add 1 to i
i++; // This is self-explanatory and doesn’t need a comment
✅ Keep comments up-to-date with your code.
Good comments can greatly improve code readability and maintainability. Whether you're collaborating on a team or revisiting your own code after months, well-placed comments will always make your job easier.
Use single-line and multi-line comments wisely, and consider adopting JSDoc for professional-level documentation!