Comments help developers understand code intent. **Single-line** comments use `//`. **Multi-line** comments use `/* ... */`. **JSDoc** comments (`/** ... */`) are used by documentation generators and IDEs for type hints.
1Understanding Comments
Comments help developers understand code intent. Single-line comments use //. Multi-line comments use /* ... */. JSDoc comments (/** ... */) are used by documentation generators and IDEs for type hints.
Write comments to explain WHY, not WHAT. The code itself should be readable enough to show what it does.
// This calculates the compound interest
function compound(principal, rate, years) {
/* Formula: P * (1 + r)^t
Used for savings/loan calculations */
return principal * Math.pow(1 + rate, years);
}
console.log(compound(1000, 0.05, 10));2Practical Example
Here is a real-world application of Comments showing how it is used in production JavaScript code.
/**
* Greet a user by name.
* @param {string} name - The user's name
* @returns {string} The greeting message
*/
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice'));3Best Practices
Follow these guidelines when working with Comments:
1. Comment complex algorithms and business logic
2. Use JSDoc for public APIs and library functions
3. Remove dead code instead of commenting it out
Tip: Write comments to explain WHY, not WHAT. The code itself should be readable enough to show what it does.
// This calculates the compound interest
function compound(principal, rate, years) {
/* Formula: P * (1 + r)^t
Used for savings/loan calculations */
return principal * Math.pow(1 + rate, years);
}
console.log(compound(1000, 0.05, 10));