Sub topic 2
Documenting Parameters and Return Values
A function's contract is mostly what goes in and what comes out. @param and @returns are the JSDoc tags that describe that contract. They are also the tags you will write most often. Tools read them in three ways: the jsdoc generator turns them into HTML tables, editors show them in hover tooltips and autocomplete, and TypeScript's checker uses them to catch wrong arguments.
This chapter assumes you can write JavaScript functions, including default parameters, rest parameters, destructuring, and async functions. It also assumes you know the basic shape of a JSDoc block from the previous chapter: /** ... */, a description, then tags. Type syntax gets only light use here. The next chapter covers unions, arrays, objects, and nullable types in full.
The Shape of a @param Tag
A @param tag has four parts, and only the name is strictly required:
/**
* Calculates a price including tax.
* @param {number} price - The base price.
* @param {number} [taxRate=0.2] - Tax rate as a fraction.
* @returns {number} The price with tax applied.
*/
function withTax(price, taxRate = 0.2) {
return price * (1 + taxRate);
}
console.log(withTax(100)); // 120
console.log(withTax(100, 0.1)); // 110.00000000000001Reading @param {number} price - The base price. from left to right:
| Part | Example | Purpose |
|---|---|---|
| Tag | `@param` | Marks this line as a parameter description. `@arg` and `@argument` are synonyms. |
| Type | `{number}` | The expected type, always in curly braces. |
| Name | `price` | Must match the parameter name in the code. |
| Separator | `-` | Optional hyphen. It makes the line easier to read and is common convention. |
| Description | `The base price.` | Free text. It can continue onto the next lines. |
Write one @param per parameter, in the same order as the function signature. The jsdoc tool lists parameters in the order of the tags, not the order of the code. If the tags are out of order, the generated table is misleading. TypeScript matches tags by name, so for type checking the order matters less, but readers still expect the two to line up.
Descriptions can span several lines. Any text after the name, up to the next tag, belongs to that parameter:
/**
* Truncates text to a maximum length.
* @param {string} text - The input text.
* @param {number} max - Maximum length, including the ellipsis.
* Values below 1 return an empty string.
* @returns {string} The truncated text.
*/
function truncate(text, max) {
if (max < 1) return '';
return text.length <= max ? text : text.slice(0, max - 1) + '…';
}
console.log(truncate('Documentation', 6)); // "Docum…"Optional Parameters and Default Values
You mark an optional parameter by wrapping its name in square brackets. You document a default value by adding =value inside the brackets.
/**
* Pads a number with leading zeros.
* @param {number} n - The number to pad.
* @param {number} [width] - Total width. Defaults to the number's own length.
* @param {string} [fill="0"] - Character used for padding.
* @returns {string} The padded string.
*/
function pad(n, width, fill = '0') {
const s = String(n);
return s.padStart(width ?? s.length, fill);
}
console.log(pad(7, 3)); // "007"
console.log(pad(7, 3, ' ')); // " 7"
console.log(pad(42)); // "42"There is an older, Closure Compiler style that puts the marker in the type instead: @param {number=} width. TypeScript and jsdoc both accept it. The bracket form is more common, and it is the only form that can carry a default value, so prefer it.
Under TypeScript checking, an optional parameter without a default has the type T | undefined inside the function body. In pad, width is number | undefined, which is why the code uses width ?? s.length. A parameter with a default in the code is never undefined inside the body, even though callers may leave it out.
Rest Parameters
For a rest parameter, put ... in front of the element type. The type describes one element, not the whole array:
/**
* Adds any number of values.
* @param {...number} values - The numbers to add.
* @returns {number} The sum, or 0 when called with no arguments.
*/
function sum(...values) {
return values.reduce((total, v) => total + v, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum()); // 0A common mistake is writing {...number[]}. That would mean "any number of arrays of numbers", which TypeScript reads as number[][], so a call like sum(1, 2) fails type checking.
Options Objects and Destructured Parameters
Many functions take a single options object. You document its properties by adding one @param line per property, named with dot notation from the parameter's name:
/**
* Builds a server URL.
* @param {Object} options - Connection options.
* @param {string} options.host - Server hostname.
* @param {number} [options.port=8080] - Server port.
* @param {boolean} [options.secure=false] - Use HTTPS instead of HTTP.
* @returns {string} The full URL.
*/
function serverUrl({ host, port = 8080, secure = false }) {
return `${secure ? 'https' : 'http'}://${host}:${port}`;
}
console.log(serverUrl({ host: 'localhost' })); // "http://localhost:8080"
console.log(serverUrl({ host: 'example.com', port: 443, secure: true })); // "https://example.com:443"Destructured parameters have no name in the code, so you choose one (options here) and use it consistently as the prefix. TypeScript links the root tag to the parameter by position and the dotted tags to the destructured properties by name. The parent line @param {Object} options must come before its properties, and its type should be Object or object.
If the whole options object can be omitted, mark the parent optional and give the destructuring a default in code. Otherwise a call with no arguments throws:
/**
* Formats a date as YYYY-MM-DD.
* @param {Date} date - The date to format.
* @param {Object} [options] - Formatting options.
* @param {boolean} [options.utc=false] - Use UTC fields instead of local time.
* @returns {string} The formatted date.
*/
function isoDay(date, { utc = false } = {}) {
const y = utc ? date.getUTCFullYear() : date.getFullYear();
const m = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
const d = utc ? date.getUTCDate() : date.getDate();
return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
}
console.log(isoDay(new Date(Date.UTC(2026, 0, 5)), { utc: true })); // "2026-01-05"When the same options shape appears in several functions, repeating the dotted lines gets tedious. Chapter 4 shows how to define the shape once with @typedef.
Documenting Return Values
@returns {Type} description describes what the function gives back. @return is a synonym. Pick one and use it across the codebase; most projects use @returns.
The description should say what the value means, especially for edge cases. "The sum" tells the reader little. "The sum, or 0 when called with no arguments" answers the question they will actually have.
Functions That Return Nothing
If a function returns nothing, you have two reasonable choices: omit @returns, or write @returns {void}. Omitting it is the more common choice. TypeScript infers void from the code anyway. Don't write @returns {undefined} for a function without a return statement. It is technically accurate, but it suggests that callers might want to use the value.
Async Functions and Promises
An async function always returns a Promise, so the documented type is the Promise, not the value it resolves to:
/**
* Waits for a number of milliseconds.
* @param {number} ms - Delay in milliseconds.
* @returns {Promise<string>} Resolves with a message once the delay has passed.
*/
async function wait(ms) {
await new Promise((resolve) => setTimeout(resolve, ms));
return `waited ${ms}ms`;
}
wait(100).then(console.log); // "waited 100ms"Writing @returns {string} here is a frequent error. With // @ts-check enabled, TypeScript rejects it: the return type of an async function must be the global Promise<T> type. For a function that resolves with nothing, use Promise<void>.
Functions That Return Different Things
If the return type depends on input or state, say so in both the type and the description:
/**
* Finds the index of the first negative number.
* @param {number[]} values - Numbers to search.
* @returns {number} The index, or -1 if every value is zero or positive.
*/
function firstNegative(values) {
return values.findIndex((v) => v < 0);
}
/**
* Looks up a setting.
* @param {Map<string, string>} settings - The settings store.
* @param {string} key - Setting name.
* @returns {string | undefined} The value, or undefined if the key is missing.
*/
function getSetting(settings, key) {
return settings.get(key);
}
console.log(firstNegative([3, -1, 4])); // 1
console.log(getSetting(new Map([['mode', 'dark']]), 'mode')); // "dark"The union string | undefined is covered in the next chapter. For now, the point is that the type is honest about the missing case, and the description explains when that case happens.
What Tools Do With Missing Pieces
You don't have to annotate everything. It helps to know what happens when you leave a piece out:
| You write | jsdoc HTML output | TypeScript with checkJs |
|---|---|---|
| No `@param` at all | Parameter listed without type or description | Type is `any`, or an error under `noImplicitAny` |
| `@param price` (no type) | Name shown, type column blank | Still `any` |
| `@param {number} price` | Full row | `number` |
| No `@returns` | No "Returns" section | Return type inferred from the code |
| `@param {number} cost` when the code says `price` | Shows a parameter that doesn't exist | Error: the JSDoc `@param` tag has name `cost`, but there is no parameter with that name |
The last row is the error you will see most in practice. It usually appears after someone renames a parameter and forgets the comment. Chapter 8 shows how to turn on that checking, and Chapter 11 shows how eslint-plugin-jsdoc catches the same mismatch at lint time.
Common Mistakes
- Missing braces around the type.
@param number pricemakesnumberthe name andpricethe start of the description. Always write{number}. - Brackets on the type instead of the name.
@param {[number]} widthis a tuple type, not an optional parameter. The brackets go around the name:[width]. - Spaces inside the default.
[fill = "0"]works in TypeScript, but somejsdocversions and plugins parse it badly. Write[fill="0"]. - Restating the type in words. "@param {number} count - A number" adds nothing. Describe units, ranges, and meaning instead: "Number of retries, from 0 to 5."
- Forgetting the Promise. Async functions return
Promise<T>, never bareT. - Stale defaults. The bracketed default drifts from the code with no warning.
Exercise
Write a complete JSDoc block for this function: function repeat(text, times = 2, ...separators) { return Array(times).fill(text).join(separators[0] ?? ''); }. Document that times is optional with a default, that separators is a rest parameter of strings where only the first one is used, and what the function returns.
Show answer
/* Repeats a string. @param {string} text - Text to repeat. @param {number} [times=2] - How many copies to produce. @param {...string} separators - Separator strings; only the first is used, and none means no separator. @returns {string} The copies joined by the separator. / Each tag goes on its own line in a real file. The key points: [times=2] marks the default, {...string} gives the element type of the rest parameter rather than string[], and the description explains that the extra separators are ignored.
Exercise
A teammate documents async function loadConfig(path) with @returns {Object} The parsed config. Under // @ts-check this is flagged. What is wrong, and how should the tag read?
Show answer
An async function always returns a Promise, so the documented return type must be a Promise. Write @returns {Promise<Object>} Resolves with the parsed config. Better still, replace Object with a named shape defined using @typedef, which Chapter 4 covers.
Exercise
The function function connect({ host, timeout = 1000 } = {}) is documented with @param {Object} opts, @param {string} opts.host, and @param {number} opts.timeout. Name two problems with this documentation.
Show answer
First, opts.timeout has a default in the code, so it should be written [opts.timeout=1000]. Second, the whole object defaults to {}, so the parent should be optional ([opts]). Callers may omit it, and host may then be undefined, which the description should mention. If host really is required, the code should not default the object to {}.