Skip to main content

JavaScript Comments

When you're writing code, it's not just about making it work - it's also about making it understandable. Comments are notes that you add to your code that are ignored by the JavaScript interpreter but can be read by humans. They are essential tools for explaining your code, documenting functionality, and making your programs more maintainable.

Why Use Comments?

Comments serve several important purposes:

  • Documentation: They explain what your code does
  • Clarification: They help others (and your future self) understand complex logic
  • Debugging: They can be used to temporarily disable code
  • Organization: They can help structure your code into logical sections

Types of JavaScript Comments

JavaScript supports two types of comments: single-line comments and multi-line comments.

Single-line Comments

Single-line comments start with two forward slashes (//) and continue until the end of the line. They're perfect for brief explanations.

javascript
// This is a single-line comment
let name = "John"; // You can also place comments at the end of a line

Multi-line Comments

Multi-line comments start with /* and end with */. Everything between these markers is ignored by JavaScript. These are useful for longer explanations or documenting functions.

javascript
/* This is a
multi-line comment that
can span several lines */

/* You can use multi-line comments
to provide detailed information about:
- What a function does
- How to use a particular piece of code
- Important considerations
*/

Best Practices for Writing Comments

1. Be Clear and Concise

Good comments explain "why" rather than "what":

javascript
// BAD: Increment counter by 1
counter++;

// GOOD: Increment user activity counter to track engagement
counter++;

2. Comment Complex Logic

Comments are particularly useful for explaining complex or non-intuitive code:

javascript
// Calculate discount based on multiple factors:
// - Membership status (10% discount for members)
// - Seasonal promotions (15% additional discount in December)
// - Loyalty points (1% discount for every 100 points)
let finalPrice = basePrice * (1 - memberDiscount) * (1 - seasonalDiscount) - (loyaltyPoints / 100) * basePrice;

3. Use JSDoc Format for Functions

For functions, consider using JSDoc-style comments to document parameters and return values:

javascript
/**
* Calculates the total price including tax
* @param {number} price - The base price of the item
* @param {number} taxRate - The tax rate as a decimal (e.g., 0.07 for 7%)
* @return {number} The total price including tax
*/
function calculateTotalPrice(price, taxRate) {
return price * (1 + taxRate);
}

Comments for Debugging

Comments can be useful for temporarily "commenting out" code during development:

javascript
function testFunction() {
console.log("First part works");

// The line below has an issue we're debugging
// problematicFunction();

console.log("Continuing with the rest");
}

Real-world Example: Commented Form Validation

Here's an example of how comments might be used in a real application:

javascript
/**
* Validates a user registration form
* @param {object} formData - The form data to validate
* @return {object} Result with isValid flag and any error messages
*/
function validateForm(formData) {
const errors = {};

// Check if email is valid
if (!formData.email || !formData.email.includes('@')) {
errors.email = "Please enter a valid email address";
}

// Password must be at least 8 characters with numbers and letters
if (!formData.password || formData.password.length < 8) {
errors.password = "Password must be at least 8 characters";
} else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(formData.password)) {
// Using regex to verify password has both letters and numbers
errors.password = "Password must contain both letters and numbers";
}

// Check if passwords match
if (formData.password !== formData.confirmPassword) {
errors.confirmPassword = "Passwords do not match";
}

return {
isValid: Object.keys(errors).length === 0,
errors: errors
};
}

Avoiding Excessive Comments

While comments are helpful, too many comments can make your code harder to read. Aim for clean, self-documenting code with strategic comments:

javascript
// BAD: Too many obvious comments
// Declare a variable for user name
const userName = "John";
// Check if user name exists
if (userName) {
// Print welcome message
console.log("Welcome");
}

// BETTER: Only comment what's necessary
const userName = "John";
// Only greet users who have provided their name
if (userName) {
console.log("Welcome");
}

Summary

Comments are a vital part of writing maintainable and collaborative code. They help explain your thought process, document functionality, and make your code more accessible to others. Remember:

  • Use single-line comments (//) for brief explanations
  • Use multi-line comments (/* */) for detailed documentation
  • Comment on the "why" rather than the "what"
  • Use comments to explain complex logic
  • Avoid excessive or obvious comments
  • Consider JSDoc format for documenting functions

By mastering the art of commenting, you'll make your code more professional and easier to maintain, both for others and for your future self.

Exercises

  1. Take an existing JavaScript function you've written and add appropriate comments using the best practices discussed.
  2. Practice converting some single-line comments to JSDoc format.
  3. Review some code you wrote previously and identify places where comments would make the code more understandable.
  4. Find examples of "bad" comments in existing code and rewrite them to be more helpful.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)