# How to Make Cursor Add Code Comments

- Tool: Cursor
- Difficulty: Beginner
- Time required: 10 min
- Compatibility: Cursor Free/Pro, TypeScript/JavaScript
- Last updated: March 2026

## TL;DR

Make Cursor add JSDoc comments automatically by creating .cursorrules that require documentation on all exported functions, using Cmd+K to add comments to existing code inline, and leveraging Composer to document entire files at once. Cursor generates accurate JSDoc when it can see the function's TypeScript types and implementation.

## Automating Code Documentation with Cursor

Cursor can generate accurate JSDoc comments that describe parameters, return types, exceptions, and usage examples. The key is giving it clear documentation standards through rules and referencing the actual code with @file so it produces comments that match the implementation. This tutorial covers inline commenting with Cmd+K, bulk documentation with Composer, and rules that make documentation a default behavior.

## Before you start

- Cursor installed (Free or Pro)
- A TypeScript or JavaScript project with exported functions
- Basic understanding of JSDoc comment syntax

## Step-by-step guide

### 1. Add documentation rules to .cursorrules

Create rules that define your documentation standards. Specify which elements need JSDoc, what tags to include, and the level of detail expected. Cursor follows these rules when generating new code and when adding comments to existing code.

```
# .cursorrules

## Documentation Rules
- ALL exported functions must have JSDoc comments
- Include: @param (with type and description), @returns, @throws, @example
- Internal/private functions: brief single-line comment only
- React components: document props interface, not the component function
- Use @see for references to related functions
- Keep descriptions concise: 1-2 sentences max
- Do not document self-evident getters/setters
- Examples should be runnable TypeScript, not pseudocode
```

**Expected result:** Cursor includes JSDoc comments on all exported functions in generated code.

### 2. Add JSDoc to existing functions with Cmd+K

Select an existing function in your editor, press Cmd+K, and ask Cursor to add JSDoc. Cursor reads the function signature, parameter types, and implementation to generate accurate documentation. This is the fastest way to document individual functions.

```
// Select a function in your editor, press Cmd+K and type:
// Add a JSDoc comment to this function with:
// @param tags for each parameter with type and description
// @returns with type and description
// @throws if any errors are thrown
// @example with a realistic usage example
```

> Pro tip: Select multiple functions at once (or the entire file with Cmd+A) and Cmd+K will add JSDoc to all of them in a single pass.

**Expected result:** The selected function gets a complete JSDoc comment block above it with all specified tags.

### 3. Document entire files with Composer

For bulk documentation, use Composer (Cmd+I) to add JSDoc to every exported function in a file. Reference the file with @file and specify your documentation standards. Composer handles multi-function files efficiently.

```
// Prompt to type in Cursor Composer (Cmd+I):
// @src/utils/orderCalculator.ts
// Add JSDoc comments to every exported function in this file.
// For each function include:
// - Brief description (1 sentence)
// - @param for each parameter with type and purpose
// - @returns with type and what it represents
// - @throws if the function throws errors
// - @example with realistic usage
// Do NOT modify any function implementations — only add comments.
```

> Pro tip: Add 'Do NOT modify any function implementations' to prevent Cursor from changing your code while adding documentation.

**Expected result:** Every exported function in the file gets complete JSDoc documentation without any code changes.

### 4. Create an auto-attaching documentation rule

Create a .cursor/rules/documentation.mdc that auto-attaches for all source files. This ensures documentation standards apply whenever Cursor generates or edits code, without needing to mention documentation in every prompt.

```
---
description: JSDoc documentation standards
globs: "src/**/*.ts, src/**/*.tsx, lib/**/*.ts"
alwaysApply: false
---

- Every exported function MUST have JSDoc with @param, @returns, @example
- Every exported interface/type MUST have a description comment
- Every exported class MUST have a class-level JSDoc
- React components: document the Props interface, not the component
- Use @see to reference related functions in the same module
- Keep descriptions under 2 sentences
- @example code must be valid TypeScript that compiles
```

**Expected result:** Documentation rules auto-attach for all TypeScript source files.

## Complete code example

File: `src/utils/orderCalculator.ts`

```typescript
/**
 * Calculates the total price for an order including all line items.
 *
 * @param order - The order containing items with prices and quantities
 * @returns The total price in cents as an integer
 * @throws {Error} If any item has a negative price
 * @example
 * ```typescript
 * const total = calculateOrderTotal({
 *   items: [
 *     { name: 'Widget', priceCents: 1000, quantity: 2 },
 *     { name: 'Gadget', priceCents: 2500, quantity: 1 },
 *   ],
 * });
 * console.log(total); // 4500
 * ```
 */
export function calculateOrderTotal(order: Order): number {
  return order.items.reduce((sum, item) => {
    if (item.priceCents < 0) {
      throw new Error(`Invalid price for item: ${item.name}`);
    }
    return sum + item.priceCents * item.quantity;
  }, 0);
}

/**
 * Applies a discount to a subtotal amount.
 *
 * @param subtotalCents - The original amount in cents
 * @param discount - The discount to apply (percentage or fixed amount)
 * @returns The discounted amount in cents, minimum 0
 * @example
 * ```typescript
 * const discounted = applyDiscount(10000, { type: 'percent', value: 10 });
 * console.log(discounted); // 9000
 * ```
 * @see calculateOrderTotal
 */
export function applyDiscount(
  subtotalCents: number,
  discount: Discount
): number {
  const reduction =
    discount.type === 'percent'
      ? Math.floor(subtotalCents * (Math.min(discount.value, 100) / 100))
      : discount.value;

  return Math.max(0, subtotalCents - reduction);
}

/** Order containing line items for price calculation. */
export interface Order {
  items: OrderItem[];
}

/** A single line item in an order. */
export interface OrderItem {
  name: string;
  priceCents: number;
  quantity: number;
}

/** Discount that can be applied to an order subtotal. */
export interface Discount {
  type: 'percent' | 'fixed';
  value: number;
}
```

## Common mistakes

- **Asking Cursor to add comments without specifying which tags to include** — Without specific instructions, Cursor adds minimal comments that only restate the function name without useful parameter or return descriptions. Fix: Always specify required tags: @param, @returns, @throws, @example in your prompt or .cursorrules.
- **Not preventing code modifications during documentation** — Cursor may 'improve' function implementations while adding documentation, introducing bugs or changing behavior. Fix: Include 'Do NOT modify any function implementations — only add comments' in your documentation prompt.
- **Documenting every function including trivial getters** — JSDoc on self-evident functions like getName() or getId() adds noise without value and increases maintenance burden. Fix: Add a rule: 'Do not document self-evident getters, setters, or single-line utility functions.'

## Best practices

- Create .cursorrules requiring JSDoc on all exported functions with specific tag requirements
- Use Cmd+K for quick inline documentation of individual functions
- Use Composer for bulk documentation of entire files
- Require @example tags with runnable TypeScript code for complex functions
- Document interfaces and types alongside functions for complete API documentation
- Add 'Do NOT modify implementations' to all documentation prompts
- Use auto-attaching .cursor/rules/ for consistent documentation across the project

## Frequently asked questions

### Can Cursor add JSDoc to an entire project at once?

Not in a single prompt. Process one file at a time in Composer sessions for best results. You can create a script that lists undocumented files and process them sequentially.

### Does Cursor generate accurate @example code?

Yes, when it can see the function's TypeScript types and implementation. Reference the file with @file so Cursor reads the actual signature. Examples may need minor adjustments for import paths.

### Should I use JSDoc or TypeScript types for documentation?

Use both. TypeScript types handle parameter and return types. JSDoc adds descriptions, examples, and thrown error documentation that types cannot express. Cursor can generate both together.

### How do I prevent Cursor from adding redundant comments?

Add a rule: 'Do not add comments that restate what the code does. Only document why, edge cases, and non-obvious behavior.' This eliminates comments like '// returns the name' above getName().

### Can Cursor generate documentation in Python docstring format?

Yes. Specify 'Use Google-style Python docstrings' or 'Use NumPy docstring format' in your .cursorrules. Cursor adapts to any documentation format when instructed.

---

Source: https://www.rapidevelopers.com/cursor-tutorial/how-to-prompt-cursor-ai-to-generate-jsdoc-style-comments-automatically-for-each-function
© RapidDev — https://www.rapidevelopers.com/cursor-tutorial/how-to-prompt-cursor-ai-to-generate-jsdoc-style-comments-automatically-for-each-function
