Comments
Use comments to explain code or temporarily disable lines.
Quick Summary
Comments are ignored by the JavaScript runtime, so they don't change program behavior. Use them to clarify intent, document tricky logic, or leave notes for future you and teammates. Good comments explain WHY code does something, not WHAT it does (the code itself shows that). Avoid over-commenting obvious code, but do comment complex algorithms, business logic, and workarounds.
Why Comments Matter
Comments serve multiple purposes in programming:
- Documentation: Explain the purpose of functions, classes, or modules
- Clarification: Describe complex algorithms or non-obvious logic
- TODOs: Mark areas that need future work
- Debugging: Temporarily disable code without deleting it
Types of Comments in JavaScript
Single-line comments start with // and continue to the end of the line:
// This is a single-line comment
const price = 19.99; // Price in USD
Multi-line comments are wrapped in /* */ and can span multiple lines:
/*
This function calculates the total price
including tax and any applicable discounts.
Author: Development Team
Last updated: 2024
*/
function calculateTotal(price, tax, discount) {
return (price + tax) - discount;
}
Comment Best Practices
- Don't state the obvious:
const count = 0; // Set count to 0is unnecessary - Explain the "why":
const count = 0; // Reset for new user sessionis helpful - Keep comments updated: Outdated comments are worse than no comments
- Use TODO/FIXME tags:
// TODO: Add error handling for edge cases
Try It Yourself
Here's a practical example you can try. Copy this code and run it in your browser's console (press F12 to open developer tools) or in the Code Playground.
// Single-line: explain a tricky calculation
const total = price * 1.08; // Add 8% sales tax
// Temporarily disable code for debugging
// console.log("Debug:", total);
/* Multi-line comment for documentation
This function processes user input
and returns formatted output */
function processInput(input) {
return input.trim().toLowerCase();
}Key Takeaways
- ✓Use comments to explain code or temporarily disable lines.
- ✓Practice with real code examples to solidify your understanding
- ✓This concept builds the foundation for more advanced topics
Related Learning Resources
Continue your programming journey with these related tutorials: