Clean Code

Right Balance: Best Practices for Code Comments in TypeScript

I've seen both extremes. A codebase with zero comments where nobody could understand the business rules buried in the logic. And a codebase where every li...

19 Apr 2024

Right Balance: Best Practices for Code Comments in TypeScript

I've seen both extremes. A codebase with zero comments where nobody could understand the business rules buried in the logic. And a codebase where every line had a comment — including i++ // increment i — drowning the actual code in noise.

Both are wrong. Comments are a tool. Like any tool, the value depends on how you use it.

The one rule: comment the why, not the what

Good code tells you what it does. Comments should tell you why it does it that way.

Typescript
// BAD: restates the code
const total = price * quantity; // multiply price by quantity

// GOOD: explains a non-obvious decision
const total = price * quantity; // tax is applied at checkout, not here

If a comment describes what the code does, the code isn't clear enough. Fix the code, not the comment.

When to comment

Complex business rules. If the logic reflects a legal requirement, a stakeholder decision, or a non-obvious constraint, write a comment. Future developers won't have the context you had.

Non-obvious algorithms. If the approach isn't straightforward, explain why you chose it. Link to the algorithm, the spec, or the conversation that led to the decision.

Workarounds and hacks. If you're working around a bug in a library or an API quirk, say so. Add a link to the issue tracker. Without context, someone will "fix" your workaround and reintroduce the bug.

TODO and FIXME markers. Use TODO for planned improvements and FIXME for known issues. But treat them as temporary — if a TODO sits for months, it's not a plan, it's a wish.

When not to comment

Obvious code. getUser() doesn't need a comment explaining it gets a user. return total doesn't need // return the total.

Code that should be refactored. If a section is so complex it needs a paragraph of explanation, the real fix is to simplify the code. Extract a function. Rename a variable. Make the code speak for itself.

Changelog in comments. That's what version control is for. Don't leave // Added by John on 2024-03-15 in the code.

Keep a consistent style

Pick a commenting style for your project. JSDoc for public APIs. Inline comments for tricky logic. Be consistent. Mixed styles create visual noise.

The trade-off

Too few comments and tribal knowledge evaporates when people leave the team. Too many comments and the noise drowns the signal — plus stale comments actively mislead.

The sweet spot: comment decisions, constraints, and workarounds. Let the code explain the mechanics. Update comments when the code changes. Delete comments that no longer apply.

Comments should age like documentation, not like milk.

Keep reading