Comments and Best Practices
Comments and Best Practices in JavaScript
Writing code that works is only the first step; writing code that is readable, maintainable, and understandable by your teammates (and future you) separates junior coders from seasoned software engineers.
1. Comment Types in JavaScript
JavaScript provides two primary syntax options for adding comments that are ignored by the JS engine:
A. Single-Line Comments (//)
Use for brief explanations of a single line:
B. Multi-Line Block Comments (/* ... */)
Use for longer architectural notes or temporary code disabling:
2. Professional Documentation: JSDoc Comments (/** ... */)
Top engineering teams use JSDoc comments. JSDoc allows code editors (like VS Code) to display rich tooltips, type hints, and autocompletion:
When you hover your mouse over calculateCourseDiscount anywhere in your codebase, VS Code will display the parameters and return types automatically!
3. When NOT to Write Comments (Code Smells)
❌ Bad: Redundant Comments
❌ Bad: Using Comments to Explain Cryptic Variable Names
✅ Clean & Self-Documenting:
4. Essential JavaScript Naming Conventions
Follow standard JavaScript community conventions:
| Identifier Type | Convention | Example |
|---|---|---|
| Variables & Properties | camelCase | userName, totalAmount, isModalOpen |
| Functions & Methods | camelCase (Verb-based) | getUserProfile(), calculateTotal(), fetchCourses() |
| Booleans | Prefix with is, has, can | isLoading, hasPermission, canSubmit |
| Classes & Components | PascalCase | UserCard, PaymentGateway, ShoppingCart |
| Global Constants | UPPER_SNAKE_CASE | MAX_RETRIES, DEFAULT_TIMEOUT_MS |
5. Enable Strict Mode: "use strict"
Strict Mode eliminates silent errors in JavaScript by converting them to throw runtime exceptions:
import/export) and React/Next.js components run in strict mode automatically.Practice Quiz
/** ... */)?"use strict"; at the top of a JavaScript file enforce?Arithmetic Operators
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Data Types | Arithmetic Operators |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.