// Writes comments that explain WHY, not WHAT the code does
# Effective Comments
Good comments explain WHY, not WHAT. Code should be self-explanatory for the WHAT.
## Bad Comments - Stating the Obvious
```javascript
// Bad - Comment repeats the code
// Increment counter by 1
counter++;
// Get user by ID
const user = getUserById(id);
// Loop through items
for (const item of items) {
// Process item
processItem(item);
}
```
## Good Comments - Explain WHY
```javascript
// Good - Explain reasoning
// Using setTimeout to avoid blocking the main thread
// during heavy computation
setTimeout(() => processLargeDataset(data), 0);
// Cache duration set to 5 minutes to balance
// freshness and API rate limits
const CACHE_DURATION = 5 * 60 * 1000;
// Retry failed requests 3 times because our payment
// provider occasionally has transient errors
const MAX_RETRIES = 3;
```
## When to Comment
### DO Comment:
- Complex algorithms or business logic
- Workarounds for bugs or limitations
- Performance optimizations
- Non-obvious decisions
- TODOs and FIXMEs
```javascript
// TODO: Replace with proper pagination when API supports it
const allItems = await fetchAllItemsAtOnce();
// FIXME: This breaks on Safari < 14 due to regex lookbehind
const pattern = /(?<=@)\w+/g;
// Workaround for IE11 not supporting Array.includes()
const hasItem = items.indexOf(searchItem) !== -1;
```
### DON'T Comment:
- Obvious code
- Bad code (refactor instead)
- Commented-out code (use git)
- What the code does (make it self-explanatory)
## Better: Self-Documenting Code
```javascript
// Instead of comments, use good names
// Bad
const d = 24; // hours in a day
// Good
const HOURS_IN_DAY = 24;
```6 matches