The Art of Readable Code: Comments & Semicolons
Writing code that a computer understands is only half the battle. Writing code that **humans** understand is the mark of a professional. In JavaScript, this battle is won with two simple tools: comments and semicolons. They are the keys to clarity and stability.
The 'Why', Not the 'What': A Philosophy of Commenting
A common mistake is writing comments that explain *what* the code is doing. Good code should be self-explanatory. Instead, your comments should explain **why** the code is doing it.
❌ Bad Comment (The 'What')
// Add 1 to i
i++;This is redundant. The code already says this.
✔️ Good Comment (The 'Why')
// Offset by 1 to match the 1-based index
i++;This explains the business logic or intent.
JSDoc: The Professional Standard
When you write a function or class, you're creating an API for other parts of your code (or other developers) to use. JSDoc is a formal syntax for multi-line comments that describes this API. Modern code editors read JSDoc to provide autocomplete and type-checking.
/**
* Calculates the total price, including tax.
*
* @param {number} price - The base price of the item.
* @param {number} [taxRate=0.07] - The tax rate (e.g., 0.07 for 7%).
* @returns {number} The final price including tax.
*/
function calculateTotal(price, taxRate = 0.07) {
// Ensure price is a positive number
if (price <= 0) return 0;
return price * (1 + taxRate);
}@paramDescribes a parameter.[taxRate=0.07]The brackets `[]` mean the parameter is optional, and `=0.07` shows its default value.{number}Describes the expected data type.@returnsDescribes what the function returns.
The Hidden Enemy: Automatic Semicolon Insertion (ASI)
JavaScript has a feature called Automatic Semicolon Insertion (ASI). If you forget a semicolon, the engine tries to guess where it should go. This "feature" is a notorious source of bugs. The most common error happens with the `return` keyword.
function getUser() {
return // <--- ASI inserts a semicolon here!
{
username: "alex"
};
}
getUser(); // Returns undefined, NOT the object!Because the `return` keyword is on its own line, ASI "helpfully" adds a semicolon after it, making your function return `undefined`. The object below it becomes "unreachable code."
Key Takeaway: Always use comments to explain the **why**. Use JSDoc for all functions. And **always** use semicolons to terminate your statements. Do not rely on ASI. This discipline will save you hours of debugging.