Comments are notes in your code that JavaScript ignores but humans can read. They help you and others understand what your code does, why it does it, and how it works. Good comments and organization make your code maintainable and professional. Let's learn how to write code that people actually want to read!
Why Comments Matter
You might wonder: "If the code works, why do I need comments?" Here's why:
- Future you: You'll forget why you wrote something a certain way
- Team collaboration: Others need to understand your code
- Complex logic: Some algorithms need explanation
- Debugging: Comments help track down issues
- Documentation: Explain how functions should be used
- Temporary disabling: Turn code off without deleting it
Martin Fowler's Rule: "Code should be self-explanatory. Use comments when the code can't speak for itself."
Single-Line Comments
Single-line comments start with // (double forward slash). Everything after // on that line is ignored by JavaScript.
Basic Syntax
// This is a single-line comment
console.log("Hello!"); // You can also add comments after code
// Comments can explain what code does
let age = 25;
// Or why you made certain decisions
let maxAttempts = 3; // Based on security requirements
// Multiple single-line comments
// can be used for longer
// explanations that span
// multiple linesCommon Uses
// 1. Explaining complex logic
let discount = price > 100 ? 0.2 : 0.1; // 20% off for orders over $100
// 2. TODO notes for yourself
// TODO: Add input validation
// TODO: Handle error cases
// TODO: Optimize this loop
// 3. Marking sections of code
// === User Authentication ===
let isLoggedIn = checkAuth();
// === Data Processing ===
let processedData = transform(data);
// 4. Temporary debugging
console.log("Debug: value =", value); // Remove before production
// 5. Noting important information
const API_KEY = "abc123"; // DO NOT commit this to version control!Single-Line Comments Practice
Experiment with // comments
console.log() to see your output in the console above.Multi-Line Comments
Multi-line comments start with /* and end with */. Everything between them is ignored, even across multiple lines.
Basic Syntax
/*
This is a multi-line comment.
It can span many lines.
Useful for longer explanations.
*/
console.log("Hello!");
/*
Multi-line comments are great for:
- Function documentation
- Longer explanations
- Temporarily disabling blocks of code
- File headers with copyright info
*/Common Uses
/*
Function: calculateTotal
Purpose: Calculate order total including tax and shipping
Parameters:
- price: Number - Base price of items
- quantity: Number - Number of items
- shipping: Number - Shipping cost
Returns: Number - Total cost
*/
function calculateTotal(price, quantity, shipping) {
const TAX_RATE = 0.08;
let subtotal = price * quantity;
let tax = subtotal * TAX_RATE;
return subtotal + tax + shipping;
}
/*
================================
USER AUTHENTICATION MODULE
================================
Handles user login, logout, and session management.
Last updated: 2024-01-15
Author: Development Team
*/
/*
IMPORTANT: This code block is disabled for testing
Remove the comment markers when ready to deploy
let database = connectToDatabase();
let users = database.getUsers();
processUsers(users);
*/Block Comments for Documentation
/**
* Validates user email address
*
* @param {string} email - The email to validate
* @returns {boolean} - True if valid, false otherwise
*
* @example
* isValidEmail("test@example.com") // returns true
* isValidEmail("invalid-email") // returns false
*/
function isValidEmail(email) {
return email.includes("@") && email.includes(".");
}
/**
* User class representing a registered user
*
* @class
* @property {string} name - User's full name
* @property {string} email - User's email address
* @property {number} age - User's age
*/
class User {
constructor(name, email, age) {
this.name = name;
this.email = email;
this.age = age;
}
}JSDoc Comments: Starting comments with /** (double asterisk) creates JSDoc comments. Many code editors use these to provide autocomplete and inline documentation.
When to Comment (and When Not To)
DO Comment When:
- Explaining WHY: The reasoning behind a decision
- Complex algorithms: Logic that's not immediately obvious
- Workarounds: Explaining why you did something unusual
- Business rules: Domain-specific logic
- TODOs and FIXMEs: Noting future improvements
- Function documentation: What it does, parameters, return value
// ✅ GOOD COMMENTS
// Using setTimeout to prevent blocking the UI during heavy calculations
setTimeout(() => processLargeDataset(), 0);
// Regex explanation: Matches email format (user@domain.com)
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// HACK: API returns date as string, converting to Date object
// TODO: Ask backend team to fix this
let date = new Date(apiResponse.dateString);
// Calculate compound interest: A = P(1 + r/n)^(nt)
let amount = principal * Math.pow((1 + rate / periods), periods * years);
// Maximum retry attempts based on SLA requirements (3 retries = 99.9% uptime)
const MAX_RETRIES = 3;DON'T Comment When:
- Stating the obvious: Code already explains itself
- Redundant information: Repeating what code does
- Outdated comments: Comments that don't match code
- Bad code excuse: Comments explaining confusing code (rewrite it!)
- Commented code: Delete it instead (use version control)
// ❌ BAD COMMENTS
// Set x to 5
let x = 5; // Obviously, the code already shows this!
// Increment i
i++; // Don't state the obvious
// This function adds two numbers
function add(a, b) {
return a + b; // The name already says it adds!
}
// Loop through array
for (let i = 0; i < array.length; i++) { // Obvious
// Get current item
let item = array[i]; // Redundant
}
// ❌ Commented-out code (delete it!)
// let oldVariable = 10;
// oldVariable = oldVariable * 2;
// console.log(oldVariable);Golden Rule: Write self-explanatory code first. Use comments to explain WHY, not WHAT. If your code needs comments to explain WHAT it does, consider rewriting it more clearly.
Writing Self-Documenting Code
The best code needs minimal comments because it's clear on its own. Use descriptive names and clear structure.
Bad vs Good Examples
// ❌ BAD: Needs comments to understand
let d = 86400; // seconds in a day
let t = d * 7; // seconds in a week
function calc(p, r, t) {
// Calculate monthly payment
return (p * r) / (1 - Math.pow(1 + r, -t));
}
// ✅ GOOD: Self-explanatory
const SECONDS_IN_DAY = 86400;
const SECONDS_IN_WEEK = SECONDS_IN_DAY * 7;
function calculateMonthlyPayment(principal, monthlyRate, totalPayments) {
return (principal * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -totalPayments));
}// ❌ BAD: Cryptic names
if (u.a > 18 && u.v === true) {
// Allow access
a = true;
}
// ✅ GOOD: Clear intent
if (user.age > 18 && user.isVerified === true) {
allowAccess = true;
}
// ✅ EVEN BETTER: Extract to function
function canAccessAdultContent(user) {
return user.age > 18 && user.isVerified;
}
if (canAccessAdultContent(user)) {
allowAccess = true;
}Code Organization Best Practices
1. Group Related Code
// ❌ BAD: Everything mixed together
let userName = "John";
let productPrice = 99.99;
let isLoggedIn = true;
let productName = "Laptop";
let userEmail = "john@example.com";
let quantity = 2;
// ✅ GOOD: Grouped by concern
// User data
let userName = "John";
let userEmail = "john@example.com";
let isLoggedIn = true;
// Product data
let productName = "Laptop";
let productPrice = 99.99;
let quantity = 2;2. Use Consistent Spacing
// ❌ BAD: Inconsistent spacing
let x=5;
let y = 10;
let z=x+y;
if(z>10){
console.log("Greater");
}
// ✅ GOOD: Consistent spacing
let x = 5;
let y = 10;
let z = x + y;
if (z > 10) {
console.log("Greater");
}3. Separate Logical Sections
// ✅ Use blank lines to separate sections
// === Configuration ===
const API_URL = "https://api.example.com";
const MAX_RETRIES = 3;
const TIMEOUT = 5000;
// === Helper Functions ===
function formatDate(date) {
return date.toISOString();
}
function validateInput(input) {
return input && input.length > 0;
}
// === Main Logic ===
function processOrder(order) {
if (!validateInput(order)) {
return null;
}
// Process the order
return {
id: order.id,
date: formatDate(new Date()),
status: "processed"
};
}4. Use Section Headers
/*
=====================================
USER AUTHENTICATION
=====================================
*/
function login(username, password) {
// Login logic
}
function logout() {
// Logout logic
}
/*
=====================================
DATA VALIDATION
=====================================
*/
function validateEmail(email) {
// Validation logic
}
function validatePhone(phone) {
// Validation logic
}5. Constants at the Top
// ✅ GOOD: All constants defined at the top
const MAX_LOGIN_ATTEMPTS = 3;
const SESSION_TIMEOUT = 1800000; // 30 minutes in milliseconds
const API_VERSION = "v2";
const DEFAULT_LANGUAGE = "en";
// Then your variables and functions
let currentAttempts = 0;
let sessionStartTime = Date.now();
function handleLogin() {
// Use the constants
if (currentAttempts >= MAX_LOGIN_ATTEMPTS) {
console.log("Too many attempts");
}
}Comment Conventions and Patterns
TODO Comments
// TODO: Add input validation
function processData(data) {
return data.map(item => item * 2);
}
// TODO: Implement error handling
// TODO: Add retry logic
function fetchUserData(userId) {
return fetch(`/api/users/${userId}`);
}
// FIXME: This calculation is incorrect for leap years
function calculateAge(birthYear) {
return new Date().getFullYear() - birthYear;
}
// HACK: Temporary workaround until API is fixed
// Remove this when backend deploys fix (ETA: 2024-02-01)
let data = response.data || [];File Headers
/**
* Shopping Cart Module
*
* Handles all shopping cart operations including:
* - Adding/removing items
* - Calculating totals
* - Applying discounts
*
* @author Development Team
* @version 2.1.0
* @since 2024-01-15
*/
// File continues...Function Documentation
/**
* Calculate the final price after discount and tax
*
* @param {number} price - Original price
* @param {number} discount - Discount percentage (0-100)
* @param {number} taxRate - Tax rate (e.g., 0.08 for 8%)
* @returns {number} Final price rounded to 2 decimal places
*
* @example
* calculateFinalPrice(100, 10, 0.08) // Returns 97.20
*/
function calculateFinalPrice(price, discount, taxRate) {
let discountAmount = price * (discount / 100);
let priceAfterDiscount = price - discountAmount;
let tax = priceAfterDiscount * taxRate;
let finalPrice = priceAfterDiscount + tax;
return Math.round(finalPrice * 100) / 100;
}Commenting for Debugging
function processUserData(users) {
console.log("DEBUG: Starting processUserData");
console.log("DEBUG: Number of users:", users.length);
let results = [];
for (let i = 0; i < users.length; i++) {
// console.log("DEBUG: Processing user", i, users[i]);
if (users[i].age >= 18) {
results.push(users[i]);
}
}
console.log("DEBUG: Results count:", results.length);
// console.log("DEBUG: Full results:", results);
return results;
}
// Temporarily disable a feature
/*
function experimentalFeature() {
// New code being tested
console.log("Experimental");
}
*/🐛 Debugging Tip:
Use comments to quickly enable/disable debug logs. Put // before console.log() to turn it off, remove // to turn it back on. This is faster than deleting and retyping.
Practical Example: Well-Commented Code
/**
* E-commerce Order Calculator
* Calculates order totals with discounts, tax, and shipping
*/
// === Configuration ===
const TAX_RATE = 0.08; // 8% sales tax
const FREE_SHIPPING_THRESHOLD = 50; // Free shipping over $50
const STANDARD_SHIPPING = 5.99;
const BULK_DISCOUNT_THRESHOLD = 100; // 10% off orders over $100
/**
* Calculate total order cost
*
* @param {number} itemPrice - Price per item
* @param {number} quantity - Number of items
* @returns {Object} Order summary with breakdown
*/
function calculateOrder(itemPrice, quantity) {
// Calculate subtotal
let subtotal = itemPrice * quantity;
// Apply bulk discount if eligible
let discount = 0;
if (subtotal >= BULK_DISCOUNT_THRESHOLD) {
discount = subtotal * 0.1; // 10% discount
subtotal = subtotal - discount;
}
// Calculate tax
let tax = subtotal * TAX_RATE;
// Determine shipping cost
let shipping = subtotal >= FREE_SHIPPING_THRESHOLD
? 0
: STANDARD_SHIPPING;
// Calculate final total
let total = subtotal + tax + shipping;
// Return detailed breakdown
return {
subtotal: subtotal.toFixed(2),
discount: discount.toFixed(2),
tax: tax.toFixed(2),
shipping: shipping.toFixed(2),
total: total.toFixed(2)
};
}
// === Usage Example ===
let order = calculateOrder(25, 3);
console.log("Order Summary:", order);Well-Organized Code Example
See comments and organization in action
console.log() to see your output in the console above.Key Takeaways
- Use
//for single-line comments - Use
/* */for multi-line comments - JavaScript completely ignores comments—they're only for humans
- Comment WHY, not WHAT (code should explain what it does)
- Write self-documenting code with descriptive names
- Use TODO/FIXME/HACK for marking future work
- Group related code together with blank lines between sections
- Use
/**for JSDoc comments (editor autocomplete) - Delete commented-out code (use version control instead)
- Keep comments up-to-date when code changes
- Don't over-comment—trust your code to speak for itself
What's Next?
You now know how to write clear, well-organized code that other developers (including future you) will appreciate. Good comments and organization aren't optional—they're essential professional skills.
In the next lesson, we'll dive deep into String Methods and Template Literals—learning how to manipulate text, format strings, and use powerful built-in string methods to work with text data effectively.
📝 Practice Challenge:
Before moving on, try this:
- Take a piece of code you've written and add helpful comments
- Organize it into logical sections with headers and blank lines
- Write a function with JSDoc-style documentation
- Find any obvious comments (that just repeat the code) and remove them
- Add TODO comments for features you plan to implement later