Sub topic 12
What to Document and Keeping It Accurate
The earlier chapters covered how to write JSDoc. This chapter covers which comments are worth writing and how to keep them true after the code changes. A comment that is wrong does more harm than a missing one, because readers trust it.
This chapter assumes you can already write @param, @returns, @typedef, and @throws tags. It also assumes you have a project set up with // @ts-check or checkJs, and with eslint-plugin-jsdoc, as shown in earlier chapters.
Deciding What Deserves a Comment
Every comment costs something to maintain. Spend that effort where readers need it most.
Document the public surface first
Anything another module or another team imports is part of your API. API stands for application programming interface: the functions, classes, and types other code relies on. These exports need complete JSDoc. Callers usually read the hover tooltip in their editor and never open your source file, so the tooltip is all they get.
Internal helpers need less. A short description is often enough. If the helper's name and types already explain it, you can skip the comment.
Document the contract, not the implementation
A function's contract is the set of promises it makes: what inputs it accepts, what it returns, what it changes, and when it fails. The implementation is how it keeps those promises. Callers need the contract. The implementation can change without breaking callers, so a comment that describes it goes stale quickly.
Useful things to put in the contract:
- Units and ranges: milliseconds or seconds, 0–1 or 0–100, inclusive or exclusive bounds.
- What
null,undefined, or an empty array means in a return value. - Side effects: mutating arguments, writing to disk, network calls, caching.
- Failure behavior: whether the function throws, returns
null, or returns a rejected promise. - Performance traits that callers depend on, such as "runs in linear time" or "makes one request per call".
Compare a weak comment with a strong one
This comment only repeats what the code already says:
/**
* Gets the user.
* @param {string} id - The id.
* @returns {Promise<object|null>} The user.
*/
export async function getUser(id) {
const res = await fetch(`/api/users/${encodeURIComponent(id)}`);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}This version states the contract a caller actually needs:
/**
* Fetches a user record from the API. Makes one network request per call;
* results are not cached.
* @param {string} id - The user's unique identifier. It is URL-encoded before sending.
* @returns {Promise<object|null>} The user record, or `null` if no user has this id.
* @throws {Error} If the server responds with any non-404 error status.
*/
export async function getUser(id) {
const res = await fetch(`/api/users/${encodeURIComponent(id)}`);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}The strong version answers questions the types cannot: whether a missing user throws or returns null, and whether calling the function twice costs two requests.
Decision flow
Mark what is not public
When a helper must be exported for technical reasons but is not meant for outside use, tag it with @private (or @ignore). The jsdoc tool leaves @private symbols out of the generated site unless you pass -p. @ignore symbols never appear. This keeps the published docs limited to what you support.
/**
* Normalizes whitespace before parsing. Exported only for tests.
* @private
* @param {string} text
* @returns {string}
*/
export function normalize(text) {
return text.replace(/\s+/g, ' ').trim();
}What Not to Write
Some comments add noise and nothing else:
- Restating the name: "
getNamegets the name." - Types the checker already infers, on local variables inside a function. Annotate inputs and outputs, and let TypeScript infer the rest.
- History: "Changed by Sam in March to fix bug #412." Version control records that. Put it in the commit message.
- Commented-out code inside a doc block. It confuses
jsdocand readers. - Promises you cannot keep, such as "always fast" or "thread-safe" without evidence.
How Comments Go Stale
Documentation drifts in predictable ways. If you know the patterns, you can catch each one with a tool or a habit.
Common drift errors
- Renamed parameters. The code says
userId, but the comment still says@param id. - Changed types. A function that used to take a
stringnow takesstring | number, but the JSDoc was never updated. - Changed failure behavior. The function used to throw and now returns
null, but@throwsis still there. - Broken examples. The
@exampleoutput no longer matches what the function returns. - Copy-paste comments. A block copied from a similar function describes the wrong behavior.
- Dead links. A
{@link}points to a symbol that was renamed or deleted.
Which tools catch which drift
No single tool checks everything. The table shows what each layer catches.
| Drift | `checkJs` / `@ts-check` | `eslint-plugin-jsdoc` | Tests | Code review |
|---|---|---|---|---|
| `@param` name doesn't match the code | Reports it in strict setups | `check-param-names` | No | Yes |
| Missing `@param` or `@returns` | No | `require-param`, `require-returns` | No | Yes |
| Wrong type in a tag compared with usage | Yes | Partially (`check-types` checks only syntax) | Sometimes | Sometimes |
| Unknown type name | Yes | `no-undefined-types` | No | Sometimes |
| `@throws` no longer true | No | `require-throws` (flags missing tags only) | If tested | Yes |
| `@example` output wrong | No | No | Yes, if mirrored in a test | Sometimes |
| Description prose is wrong | No | No | No | Only here |
The pattern is clear. Machines check structure and types. Only people check whether the prose is true. Automate what you can so reviewers can spend their attention on the prose.
Automating Accuracy
Tighten the lint rules
The recommended config from the linting chapter is a good start. Add a few rules that target drift directly:
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
jsdoc.configs['flat/recommended'],
{
rules: {
'jsdoc/require-jsdoc': ['warn', { publicOnly: true }],
'jsdoc/require-description': 'warn',
'jsdoc/check-param-names': 'error',
'jsdoc/require-throws': 'warn',
},
},
];publicOnly: true asks for JSDoc on exported symbols only. That matches the "public surface first" rule above and keeps private helpers from filling up with empty comments.
Keep examples honest with tests
An @example block is code that nothing runs. One simple fix is to copy each example into a test, so a behavior change breaks the build instead of leaving the docs silently wrong.
// src/slug.js
/**
* Converts a title into a lowercase, hyphen-separated URL slug.
* Runs of non-alphanumeric characters become a single hyphen.
* @param {string} title - Any text.
* @returns {string} The slug, with no leading or trailing hyphens.
* @example
* slugify('Hello, World!'); // => 'hello-world'
*/
export function slugify(title) {
return title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
}// test/slug.test.js
import test from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from '../src/slug.js';
test('slugify matches its @example', () => {
assert.equal(slugify('Hello, World!'), 'hello-world');
});Run it with node --test. Name such tests after the example they mirror so the link between them is obvious to whoever edits either one.
Run every check in one command
Put all the checks behind one script and run it in CI (continuous integration, the automated build that runs on each push or pull request):
{
"type": "module",
"scripts": {
"check:types": "tsc -p .",
"check:lint": "eslint .",
"test": "node --test",
"check": "npm run check:types && npm run check:lint && npm test"
}
}With noEmit set in tsconfig.json, as in the type-checking chapter, tsc -p . only checks the code and writes no output files. If any step fails, the pull request fails, and drift is caught before it merges.
Habits for Code Review
Tools cover structure. These habits cover the rest:
- Read the comment in the diff. When a function body changes, check its JSDoc in the same review, even if the comment lines are unchanged. Unchanged comments on changed code are the most common source of drift.
- Check failure paths. If a
throwor areturn nullwas added or removed, the@throwsand@returnstags must change too. - Update
@deprecatedwith a replacement. A deprecation notice without{@link}to the replacement leaves callers stuck. - Regenerate the docs site occasionally. Run
npx jsdoc src -r -d docsand skim the output. Missing pages, empty descriptions, and broken links show up quickly in the rendered HTML. - Prefer deleting to guessing. If you are unsure a comment is still true and cannot check, remove the doubtful sentence instead of leaving a possible lie.
A Worked Drift Fix
Here is a function after a refactor. The code changed, but the comment did not:
/**
* Finds an item by id.
* @param {string} id - The item id.
* @returns {object} The item.
* @throws {Error} If no item matches.
*/
export function findItem(items, itemId) {
return items.find((item) => item.id === itemId) ?? null;
}The comment has four problems. The items parameter is undocumented. The id tag names a parameter that no longer exists. The function returns null instead of throwing. The return type leaves out null. Here is the corrected version:
/**
* Finds the first item whose `id` matches.
* @param {{ id: string }[]} items - Items to search. Not modified.
* @param {string} itemId - The id to look for.
* @returns {{ id: string } | null} The matching item, or `null` if none matches.
*/
export function findItem(items, itemId) {
return items.find((item) => item.id === itemId) ?? null;
}check-param-names would have flagged the parameter mismatch, and require-param would have flagged the missing items tag. The stale @throws could only be caught by a reviewer, which is why the review habits above matter.
Exercise
A teammate adds JSDoc to every local variable inside a 40-line exported function but leaves the function itself with only "Processes the order." Which of these comments are worth keeping, and what should the function's JSDoc include instead?
Show answer
Remove most of the local-variable annotations, because TypeScript infers those types and they add maintenance cost. Keep only annotations that pin down a type inference gets wrong. The exported function needs its contract: what it does to the order, each parameter with units or allowed values, the return value including any null or empty case, side effects such as database writes or emails sent, and @throws for each failure. An @example is also useful.
Exercise
Your @example for formatPrice says formatPrice(5) returns '$5.00', but after a change it now returns 'USD 5.00'. No tool reported anything. Why not, and what change to the project would catch this next time?
Show answer
Neither checkJs nor eslint-plugin-jsdoc runs @example code. They check only tag structure and types, and both versions return a string. Add a test that calls formatPrice(5) and asserts the exact output shown in the example, and run it in CI with the other checks. Then a behavior change fails the build, and whoever fixes it has to update either the code or the example.
Exercise
A function used to throw a RangeError for negative input. It now clamps negative values to 0. List every JSDoc tag that may need updating and say which tool, if any, would catch each one.
Show answer
Remove the @throws {RangeError} tag. No tool flags a stale @throws, so a reviewer has to catch it. Update the @param description to say negative values are clamped to 0. Only review catches prose changes. Update @returns if it described the range of possible results. Again, only review catches this. If an @example showed the error, update it and its mirrored test. The test will fail, which reveals the problem.