GitHub Copilot for Documentation

Writing documentation is a task most developers postpone. GitHub Copilot makes it fast enough that there is no reason to delay. In minutes, you can generate inline comments, function documentation, API references, and README files — all without leaving your editor.

Types of Documentation Copilot Generates

┌──────────────────────────────────────────────────────────┐
│  DOCUMENTATION TYPES COPILOT HANDLES                     │
├──────────────────────────────────────────────────────────┤
│  1. Inline Comments    — Explain what a line does        │
│  2. JSDoc / Docstrings — Formal function documentation   │
│  3. Block Comments     — Explain a section of code       │
│  4. README Files       — Project overview and setup      │
│  5. API Documentation  — Endpoints, parameters, returns  │
│  6. Changelog Entries  — Describe what changed and why   │
└──────────────────────────────────────────────────────────┘

Generating Inline Comments

Inline comments explain what a specific line or expression does. They are useful for complex operations that are not immediately obvious. Ask Copilot to add them by writing a comment prompt above the code block.

YOU TYPE:
// Add a comment explaining each line below
const result = data
    .filter(item => item.active)
    .map(item => ({ id: item.id, label: item.name.trim() }))
    .sort((a, b) => a.label.localeCompare(b.label));

COPILOT ADDS:
// Keep only items marked as active
const result = data
    .filter(item => item.active)
    // Transform each item to only include id and a trimmed label
    .map(item => ({ id: item.id, label: item.name.trim() }))
    // Sort alphabetically by label
    .sort((a, b) => a.label.localeCompare(b.label));

Generating JSDoc Comments (JavaScript)

JSDoc is a standard format for documenting JavaScript functions. It shows up in editor autocomplete and can be used by tools to generate HTML documentation. Copilot generates it from your function.

YOUR FUNCTION:
function paginateResults(items, page, pageSize) {
    const start = (page - 1) * pageSize;
    return items.slice(start, start + pageSize);
}

TYPE ABOVE IT:
/**

COPILOT GENERATES:
/**
 * Returns a paginated slice of an array.
 * @param {Array} items - The full array of items to paginate.
 * @param {number} page - The current page number (1-indexed).
 * @param {number} pageSize - The number of items per page.
 * @returns {Array} A subset of items for the requested page.
 * @example
 * paginateResults([1,2,3,4,5], 2, 2); // returns [3, 4]
 */

Generating Python Docstrings

Python uses docstrings for function documentation. Copilot generates them in Google, NumPy, or reStructuredText format depending on what your existing codebase uses.

YOUR FUNCTION:
def calculate_bmi(weight_kg, height_m):
    return weight_kg / (height_m ** 2)

TYPE TRIPLE QUOTES INSIDE:
def calculate_bmi(weight_kg, height_m):
    """

COPILOT GENERATES:
def calculate_bmi(weight_kg, height_m):
    """
    Calculate Body Mass Index (BMI).

    Args:
        weight_kg (float): Body weight in kilograms.
        height_m (float): Height in meters.

    Returns:
        float: The BMI value, rounded to two decimal places.

    Example:
        >>> calculate_bmi(70, 1.75)
        22.86
    """
    return weight_kg / (height_m ** 2)

Using the /doc Slash Command

Inside Copilot Chat, type /doc with your function selected to immediately generate documentation without writing a prompt.

SELECTED:
function throttle(fn, delay) {
    let lastCall = 0;
    return function(...args) {
        const now = Date.now();
        if (now - lastCall >= delay) {
            lastCall = now;
            return fn(...args);
        }
    };
}

IN CHAT: /doc

COPILOT GENERATES:
/**
 * Creates a throttled version of a function that runs at most
 * once per specified time interval.
 *
 * @param {Function} fn - The function to throttle.
 * @param {number} delay - Minimum time in milliseconds between calls.
 * @returns {Function} A throttled version of the input function.
 *
 * @example
 * const throttledScroll = throttle(handleScroll, 200);
 * window.addEventListener('scroll', throttledScroll);
 */

Writing a README File

Copilot can generate a full README.md for your project. Open a new file named README.md, write a brief comment describing your project, and let Copilot fill in the structure.

YOU TYPE IN README.md:


COPILOT GENERATES:
# Task Manager API

A RESTful API built with Node.js and Express for managing tasks and projects.

## Features
- User authentication with JWT
- Create, read, update, and delete tasks
- Assign tasks to team members
- MongoDB storage with Mongoose

## Requirements
- Node.js 18+
- MongoDB 6+

## Installation
1. Clone the repository
   git clone https://github.com/your/repo.git

2. Install dependencies
   npm install

3. Create a .env file (see .env.example)

4. Start the server
   npm start

## API Endpoints
| Method | Endpoint         | Description          |
|--------|------------------|----------------------|
| GET    | /api/tasks       | List all tasks       |
| POST   | /api/tasks       | Create a task        |
| PUT    | /api/tasks/:id   | Update a task        |
| DELETE | /api/tasks/:id   | Delete a task        |

## Testing
npm test

Documenting API Endpoints

For REST API documentation, describe the route in a comment above each endpoint handler and Copilot generates the full documentation block.

// Document this endpoint
// Method: POST
// Path: /api/users/register
// Body: { email, password, name }
// Returns: 201 with user object and JWT, or 400 on validation error
router.post('/register', async (req, res) => {

COPILOT SUGGESTS ABOVE THE ROUTE:
/**
 * @api {post} /api/users/register Register a new user
 * @apiName RegisterUser
 * @apiGroup Users
 *
 * @apiBody {String} email User's email address
 * @apiBody {String} password Minimum 8 characters
 * @apiBody {String} name Full name
 *
 * @apiSuccess {Number} status 201
 * @apiSuccess {Object} user Newly created user object
 * @apiSuccess {String} token JWT authentication token
 *
 * @apiError {Number} status 400
 * @apiError {String} message Validation error description
 */

Writing Changelog Entries

Changelogs describe what changed between software versions. Paste your git diff or a list of changes into Chat and ask Copilot to format it as a changelog entry.

YOU IN CHAT:
Write a changelog entry for version 2.3.0.
Changes:
- Added password reset via email
- Fixed bug where logout didn't clear the session cookie
- Updated the user profile page to show account creation date
- Improved API response times by 40% with query caching

COPILOT GENERATES:
## [2.3.0] - 2024-01-15

### Added
- Password reset via email verification link

### Fixed
- Logout now correctly clears the session cookie

### Changed
- User profile page displays account creation date
- API query caching reduces response times by approximately 40%

Documentation Best Practices with Copilot

Generate documentation right after writing a function — not at the end of the project. Copilot reads the code you just wrote and produces the most accurate documentation immediately. If you wait weeks, you will need to re-read your own code and may miss edge cases that were obvious to you at the time of writing.

Always read the generated documentation before committing it. Copilot occasionally misidentifies what a parameter does or describes the wrong return value. A 30-second read catches these issues before they mislead future readers of your code.

Leave a Comment

Your email address will not be published. Required fields are marked *