Sub topic 5
Examples, Errors, Links, and Deprecation
Types tell a reader what goes into a function and what comes out. They don't show how to call it, what can go wrong, where related code lives, or whether the function should still be used. JSDoc has descriptive tags for those questions: @example, @throws, @see, inline {@link}, and @deprecated.
This chapter assumes you can already write a JSDoc block with a description, @param, and @returns, and that you can read basic type expressions such as {string} and {number[]}. You should also be comfortable with ES modules and with reading hover tooltips in an editor such as VS Code.
Where Descriptive Tags Show Up
Each descriptive tag is read by two kinds of consumers. The jsdoc command-line tool turns the tags into sections of an HTML page. TypeScript's language service, which powers IntelliSense in VS Code even for plain JavaScript, reads the same tags and shows them in hover cards, completion lists, and diagnostics. The two consumers don't treat every tag the same way, and that affects what you write.
| Tag | Purpose | jsdoc HTML output | Editor (TypeScript) behavior |
|---|---|---|---|
| `@example` | Show a call and its result | Rendered as a code block | Shown in hover, formatted as code |
| `@throws` | Name an error the function raises | "Throws" section with type | Shown in hover; not enforced |
| `@see` | Point to related material | "See" list with links | Shown in hover; namepaths resolve |
| `{@link}` | Inline link inside any text | Hyperlink | Clickable link in hover |
| `@deprecated` | Mark an API as retired | "Deprecated" label | Strikethrough and a suggestion diagnostic |
Showing Usage with @example
@example takes everything after it, up to the next tag or the end of the comment, and treats it as literal code. Leading * characters and the single space after them are stripped. Indentation beyond that is kept. You can use several @example tags in one block, and each one becomes its own code sample.
/**
* Formats a number of bytes as a human-readable string.
* @param {number} bytes - A non-negative byte count.
* @param {number} [decimals=1] - Digits after the decimal point.
* @returns {string} The formatted size, such as "1.5 KB".
* @example
* formatBytes(512); // => "512 B"
* formatBytes(1536); // => "1.5 KB"
* @example
* // Control precision with the second argument
* formatBytes(1048576, 2); // => "1.00 MB"
*/
export function formatBytes(bytes, decimals = 1) {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
if (bytes < 1024) return `${bytes} B`;
let i = 0;
let value = bytes;
while (value >= 1024 && i < units.length - 1) {
value /= 1024;
i++;
}
return `${value.toFixed(decimals)} ${units[i]}`;
}
console.log(formatBytes(512));
console.log(formatBytes(1536));
console.log(formatBytes(1048576, 2));Run it with node (save it as format.mjs so the export keyword works), and it prints 512 B, 1.5 KB, and 1.00 MB, the same values the examples promise. That match matters. An example is the part of a doc comment that readers copy and paste, so it should be code that actually runs.
The jsdoc generator lets you put a caption on the first line of an example:
/**
* @example <caption>Formatting a large file size</caption>
* formatBytes(5368709120); // => "5.0 GB"
*/TypeScript's hover view doesn't understand the caption markup and shows it as raw text. If your team reads docs mostly in the editor, a leading comment line such as // Formatting a large file size reads cleanly in both places.
Gotcha: lines starting with @
The parser ends an example at the next line that begins with @. A decorator or an @-prefixed string at the start of a line inside an example gets read as a new tag, and the rest of your example disappears or turns into a bogus tag. Indent that line, or put something in front of the @, so it doesn't start the line.
Documenting Errors with @throws
@throws (alias @exception) records an error a function can raise. The syntax is @throws {Type} description, and both parts are optional. Use one tag for each distinct failure.
/**
* Withdraws money from an account balance.
* @param {number} balance - Current balance.
* @param {number} amount - Amount to withdraw.
* @returns {number} The new balance.
* @throws {TypeError} If either argument is not a finite number.
* @throws {RangeError} If amount is negative or exceeds balance.
*/
export function withdraw(balance, amount) {
if (!Number.isFinite(balance) || !Number.isFinite(amount)) {
throw new TypeError('balance and amount must be finite numbers');
}
if (amount < 0 || amount > balance) {
throw new RangeError(`cannot withdraw ${amount} from ${balance}`);
}
return balance - amount;
}
try {
withdraw(100, 250);
} catch (err) {
console.log(err instanceof RangeError, err.message);
}Two points trip people up.
First, TypeScript does not enforce @throws. JavaScript has no checked exceptions, so the type inside the braces is only documentation. The editor shows the tag text in hovers but never checks that callers handle the error, or that the function really throws that type. Accuracy is up to you.
Second, async functions don't throw to their caller. They return a rejected promise. A throw inside an async function becomes a rejection, and try/catch only catches it if the caller uses await. Writing @throws on an async function is a common convention, but say plainly that the error arrives as a rejection:
/**
* Loads a JSON config file.
* @param {string} path - File path.
* @returns {Promise<object>} Resolves with the parsed config.
* @throws {SyntaxError} The promise rejects with this if the file is not valid JSON.
*/
export async function loadConfig(path) {
const { readFile } = await import('node:fs/promises');
return JSON.parse(await readFile(path, 'utf8'));
}Document the errors a caller can reasonably handle or prevent. You don't need a @throws for every error a dependency might raise. Write one when the error is part of the function's contract: argument validation, "not found" cases, and domain rules like insufficient funds.
Cross-References with @see and {@link}
@see is a block tag that adds a "See also" entry. Its argument can be a namepath (the name of another documented symbol, such as formatBytes or Counter#increment) or a URL. {@link} is an inline tag that you place inside any text: a description, a @param explanation, a @deprecated note, or a @see.
/**
* Parses a byte string such as "1.5 KB" back into a number.
* This is the inverse of {@link formatBytes}.
* @param {string} text - A size string.
* @returns {number} The size in bytes.
* @throws {SyntaxError} If text does not match "<number> <unit>".
* @see formatBytes
* @see {@link https://en.wikipedia.org/wiki/Kilobyte Kilobyte on Wikipedia}
*/
export function parseBytes(text) {
const match = /^([\d.]+)\s*(B|KB|MB|GB|TB)$/.exec(text.trim());
if (!match) throw new SyntaxError(`invalid size: ${text}`);
const power = ['B', 'KB', 'MB', 'GB', 'TB'].indexOf(match[2]);
return Math.round(Number(match[1]) * 1024 ** power);
}{@link} accepts link text in several forms:
| Form | Example | Column |
|---|---|---|
| Target only | `{@link formatBytes}` | |
| Text after the first space | `{@link formatBytes the formatter}` | |
| Text after a pipe | `{@link formatBytes\ | the formatter}` |
| Text before the tag | `[the formatter]{@link formatBytes}` |
The space and pipe forms work in both jsdoc and TypeScript. The bracket-prefix form is jsdoc-specific, so prefer the space or pipe forms. Both tools also support {@linkcode}, which renders the link text in a monospace font, and {@linkplain}, which renders it as normal text.
Gotcha: links that silently break
A namepath link only resolves if the target is documented and in scope. In the jsdoc HTML output, a link to a name that doesn't exist renders as plain text with no warning. In the editor, TypeScript resolves the name the way it resolves identifiers in code, so a link to a symbol in another module only works if that symbol is imported or reachable. When you rename a function, its links don't update unless your editor's rename refactoring covers comments, and VS Code's rename does update {@link} references it can resolve. Search for the old name in comments anyway.
Retiring APIs with @deprecated
@deprecated marks a symbol as something callers should stop using. Write the tag with a message that says what to use instead and, if you know, when the symbol will be removed. Pair it with {@link} so the replacement is one click away.
/**
* Parses a JSON string.
* @param {string} text - The JSON text.
* @returns {unknown} The parsed value.
* @throws {SyntaxError} If the text is not valid JSON.
*/
export function parseJson(text) {
return JSON.parse(text);
}
/**
* Parses a JSON string.
* @deprecated Since 2.0. Use {@link parseJson} instead; removed in 3.0.
* @param {string} text
* @returns {unknown}
*/
export function oldParse(text) {
return parseJson(text);
}
console.log(oldParse('{"a": 1}'));In VS Code, every call to oldParse is drawn with strikethrough, and the hover shows the deprecation message. TypeScript reports it as a suggestion diagnostic ('oldParse' is deprecated.), not as an error, so tsc builds don't fail. This works even without // @ts-check, because the language service reads JSDoc in every JavaScript file.
You can deprecate more than functions: class methods, properties, @typedef types, and whole classes all accept the tag. Deprecating a single overload or one property of a typedef lets you retire part of an API without breaking the rest.
Putting It Together
A well-documented public function often uses all of these tags at once. A good order is description, @param, @returns, @throws, @example, @see, and @deprecated last when it applies. The order doesn't change the output, but a consistent order makes comments easier to scan, and the lint rules covered in a later chapter can enforce it.
Exercise
A teammate writes @throws {NotFoundError} on an async function getUser(id) and asks why VS Code never warns callers who don't wrap the call in try/catch. Explain the two reasons, and rewrite the tag so it describes the behavior accurately.
Show answer
First, TypeScript does not enforce @throws at all. JavaScript has no checked exceptions, so the tag is only documentation. Second, an async function never throws synchronously. It returns a promise that rejects, and a try/catch only catches the error if the caller awaits the call. A clearer tag is: @throws {NotFoundError} The returned promise rejects with this if no user has the given id.
Exercise
This example disappears from the generated docs after its first line. Why, and how do you fix it? /* @example class Service { @inject('db') db; } */
Show answer
The line @inject('db') starts with @ once the leading " * " is stripped, so the parser treats it as a new tag and ends the example there. Indent the decorator line (for example, write it as " @inject('db')") so it no longer begins the line, or drop the decorator from the example.
Exercise
Write a JSDoc block for a deprecated function toKB(bytes) that tells callers to use formatBytes instead, links to the replacement, includes one working example, and gives the version in which it will be removed.
Show answer
One correct answer: /* Converts bytes to kilobytes. @deprecated Use {@link formatBytes} instead; removed in 3.0. @param {number} bytes - A byte count. @returns {number} The size in kilobytes. @example toKB(2048); // => 2 / function toKB(bytes) { return bytes / 1024; }