---
name: self-commenting-code
description: Use when writing or refactoring any code — especially when you're about to add a comment explaining what a variable or function does. Good names eliminate the need for comments. Always prefer a descriptive name over an explanatory comment.
---

# Self-Commenting Code

## Overview

Code should explain itself through naming. If you need a comment to describe what something does, rename it instead.

## The Rule

Avoid comments that describe *what* code does. Write names that make the what obvious.

```typescript
// ❌ Comment required because name is meaningless
const d = new Date(); // current date
const u = users.filter(x => x.a); // active users
const calc = (p, t) => p + (p * t); // calculate price with tax

// ✅ Name makes comment unnecessary
const currentDate = new Date();
const activeUsers = users.filter(user => user.isActive);
const calculatePriceWithTax = (basePrice: number, taxRate: number) =>
  basePrice + (basePrice * taxRate);
```

## When Comments Are Appropriate

Comments are for *why*, not *what*:

```typescript
// ✅ Explains non-obvious reasoning (why, not what)
// Delay ensures the animation frame completes before measuring
await new Promise(resolve => setTimeout(resolve, 0));

// ✅ Documents an external constraint
// API returns timestamps in Unix seconds, not milliseconds
const date = new Date(timestamp * 1000);
```

Never write a comment that just restates the code in English.

## Naming Guidelines

| Pattern | ❌ Avoid | ✅ Prefer |
|---|---|---|
| Booleans | `flag`, `check`, `val` | `isActive`, `hasPermission`, `canEdit` |
| Collections | `list`, `arr`, `items` | `activeUsers`, `pendingOrders` |
| Functions | `handle`, `process`, `do` | `validateEmail`, `fetchUserById` |
| Callbacks | `x`, `i`, `el` | `user`, `index`, `element` |
| Return values | `res`, `result`, `data` | `parsedConfig`, `matchingUsers` |

## Applying to Existing Code

When you encounter a commented variable or function:
1. Read the comment
2. Turn the comment into the name
3. Delete the comment
