Sub topic 1
Anatomy of a JSDoc Comment
A JSDoc comment is an ordinary JavaScript comment written in a particular format. The JavaScript engine skips it the same way it skips any other comment. Other tools read it: your editor shows it in hover tooltips, TypeScript uses it to check types, the jsdoc command-line tool turns it into HTML pages, and linters check that it is well formed. All of these tools depend on the same few rules about how the comment is written and where it sits in the file.
This chapter covers those rules: what makes a comment a JSDoc comment, how the description and tags are laid out, how tools attach a comment to code, and the formatting mistakes that make tools ignore a comment without any warning. Later chapters cover individual tags such as @param and @returns in detail.
Prerequisites
This chapter assumes you can:
- Write JavaScript functions, objects, and ES classes.
- Use ES modules (
importandexport). - Run commands with
npmornpx. - Use a code editor such as VS Code, including hovering over a symbol to see its tooltip.
You do not need any TypeScript knowledge yet.
The Comment Delimiters
JavaScript has two comment forms: line comments (// ...) and block comments (/* ... */). A JSDoc comment is a block comment that opens with exactly two asterisks: /**.
// A line comment. Tools ignore it for documentation.
/* A plain block comment. Also ignored. */
/** A JSDoc comment. Tools read this one. */
const answer = 42;The second asterisk is the whole signal. Tools do not look at what the comment contains to decide whether it is documentation. If the comment opens with /*, it is not JSDoc, even when it contains @param tags.
Three or more asterisks do not count either. The jsdoc tool ignores comments that open with /***, which is handy for decorative banners:
/***************************
* Section: helpers
***************************/Layout of a Multi-line Comment
Most JSDoc comments span several lines. The convention is to start each inner line with a space and an asterisk:
/**
* Formats a number as a currency string.
*
* Uses the runtime's Intl support, so the output
* depends on the locale you pass.
*
* @param {number} amount - The amount to format.
* @param {string} locale - A BCP 47 locale tag such as "en-GB".
* @returns {string} The formatted amount.
*/
function formatMoney(amount, locale) {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'EUR',
}).format(amount);
}
console.log(formatMoney(1234.5, 'de-DE'));Before reading the content, tools remove the opening /**, the closing */, and the leading whitespace and asterisk on each line. The leading asterisks are optional, and a comment without them parses the same way. Keep them anyway. Editors add them automatically when you type /** and press Enter, and readers expect them.
After the markers are removed, the content has two parts in a fixed order:
- The description: free text from the start of the comment up to the first block tag.
- The block tags: each one starts with
@at the beginning of a line and runs until the next block tag or the end of the comment.
The Description
The description says what the code does and why someone would use it. Write it in full sentences. Many tools treat the first sentence as a summary and show it in short listings, such as a table of a module's functions or the first line of a completion popup. Make that first sentence work on its own.
Leave a blank line between paragraphs. Editors such as VS Code render the description as Markdown in hover tooltips, so backticks, emphasis, and lists all display properly. The jsdoc HTML generator renders Markdown only after you enable its plugins/markdown plugin, which a later chapter covers.
You can also mark the description explicitly with the @description tag (alias @desc). With the tag, the description can come after other tags:
/**
* @param {string} s
* @description Reverses a string by code point.
*/
function reverse(s) {
return [...s].reverse().join('');
}
console.log(reverse('abc')); // "cba"Most codebases put the untagged description first and use @description rarely. Choose one style and stay consistent.
Block Tags
A block tag is an @ followed by a tag name, at the start of a line (after the stripped asterisk). Its text continues across lines until the next block tag starts:
/**
* Splits a list into fixed-size chunks.
*
* @param {Array<unknown>} items - The list to split. It is not
* modified; a new array of chunks is returned.
* @param {number} size - Chunk length. Must be at least 1.
* @returns {Array<Array<unknown>>} The chunks, in order.
*/
function chunk(items, size) {
const out = [];
for (let i = 0; i < items.length; i += size) {
out.push(items.slice(i, i + size));
}
return out;
}
console.log(chunk([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]The indented second line of the first @param still belongs to that tag. The indentation is only for readability.
Most tags share a general shape, but each tag decides which parts it uses:
| Part | Example | Notes |
|---|---|---|
| Tag name | `@param` | Always required. |
| Type | `{number}` | In braces. Used by tags such as `@param`, `@returns`, `@type`. |
| Name | `size` | The identifier the tag refers to. Used by `@param`, `@property`. |
| Separator | `-` | Optional hyphen between the name and the text. Conventional and easier to read. |
| Text | `Chunk length.` | Free-form description of this item. |
Some tags take no content at all. @private and @deprecated (when used without a note) are flags.
What does and doesn't count as a tag
Only an @ at the start of a line begins a block tag. An @ in the middle of a sentence is ordinary text:
/**
* Sends mail to [email protected] when a job fails.
*/
function notifySupport() {}The reverse case can cause trouble. If a line of description happens to begin with @, for example when you mention a decorator or a scoped npm package, the parser reads it as a new tag and cuts the description off there. Reword the line, or wrap the name in backticks in the middle of a sentence:
/**
* Wraps the client from the `@aws-sdk/client-s3` package.
*/
function makeClient() {}Inline Tags
An inline tag sits inside text and is wrapped in braces: {@tagname ...}. The most common is {@link}, which creates a cross-reference:
/**
* Parses a date string. For formatting, see {@link formatDate}.
* @param {string} text
* @returns {Date}
*/
function parseDate(text) {
return new Date(text);
}
/**
* Formats a date as YYYY-MM-DD.
* @param {Date} date
* @returns {string}
*/
function formatDate(date) {
return date.toISOString().slice(0, 10);
}
console.log(formatDate(parseDate('2026-11-25T10:00:00Z')));Inline tags can appear in the description or inside a block tag's text. Don't confuse them with type expressions. {number} after @param is a type, and {@link formatDate} is an inline tag. The @ right after the brace is what separates them. A later chapter covers {@link} and the other descriptive tags.
Single-line Comments
When a comment holds only one short piece of information, you can write the whole thing on one line:
/** Maximum number of retries before giving up. */
const MAX_RETRIES = 3;
/** @type {Map<string, number>} */
const hits = new Map();
hits.set('home', MAX_RETRIES);
console.log(hits.get('home'));The one-line form follows the same rules: /** to open, a description and then tags. It is the usual style for constants, fields, and type annotations on variables.
Attaching a Comment to Code
A JSDoc comment documents the code that comes directly after it. Tools do not match comments to code by name. They look at position. Put the comment immediately above the declaration, with no other statement in between.
These are the constructs a comment can attach to:
| Construct | Example target |
|---|---|
| Function declaration | `function save() {}` |
| Variable or constant | `const limit = 10;` |
| Function expression or arrow function | `const add = (a, b) => a + b;` |
| Class declaration | `class Cache {}` |
| Method, getter, setter | `get size() {}` |
| Class field or property assignment | `this.count = 0;` |
| Object literal property | `{ /** ... */ timeout: 500 }` |
Exports work the same way. Put the comment above the whole export statement:
/**
* Adds two numbers.
* @param {number} a
* @param {number} b
* @returns {number}
*/
export const add = (a, b) => a + b;Common attachment mistakes
These mistakes all fail without any error message:
/**
* Doubles a number.
* @param {number} n
*/
const unrelated = 'oops'; // The comment attaches to this variable instead.
function double(n) {
return n * 2;
}
function triple(n) {
/**
* Triples a number.
* Inside the body, this documents the return statement, not triple.
*/
return n * 3;
}
console.log(double(2), triple(2));Python programmers often make the second mistake, because Python docstrings go inside the function body. JSDoc comments always go before the code.
The Closing Delimiter Trap
A block comment ends at the first */, wherever it appears, even in the middle of an example. Glob patterns cause this often, because src/**/*.js contains */:
/**
* Lists source files.
* Matches every file under src with the pattern src/**\/*.js
* (the backslash keeps the comment open).
* @returns {string[]}
*/
function listSources() {
return [];
}
console.log(listSources());Without the backslash, the comment would end after src/**, and the rest of the line would be parsed as code, which causes a syntax error. Escape the slash as shown, or describe the pattern in words. Regular expressions such as /a*/ cause the same problem.
Who Reads the Comment
The same comment reaches several tools. Each one reads different parts of it:
| Tool | Uses the description | Uses the types | Uses the tags |
|---|---|---|---|
| Editor tooltips (TypeScript language service) | Yes, rendered as Markdown | Yes, for IntelliSense | Most common tags |
| TypeScript with `checkJs` | No | Yes, for type errors | Type-related tags |
| `jsdoc` HTML generator | Yes | Yes, displayed | Nearly all JSDoc tags |
| `eslint-plugin-jsdoc` | Checks that it exists and is formatted | Checks syntax | Checks names and completeness |
The tools don't support exactly the same set of tags. TypeScript understands some tags, such as @satisfies, that the jsdoc generator does not, and the generator supports tags such as @memberof that TypeScript ignores. A comment that follows the shared syntax in this chapter will work with all of them, and later chapters point out where their behavior differs.
Exercises
Exercise
A teammate's comment is not showing up in editor tooltips. It reads "/ Returns the user's full name. @param {User} user /" directly above the function. What is wrong, and what is the fix?
Show answer
The comment opens with / instead of /, so tools treat it as a plain block comment. Change the opener to /* and, for readability, put the description and the @param tag on separate lines.
Exercise
In this comment, where does the description end? "/* Wraps a fetch call. @retry is handled by the caller. @param {string} url */"
Show answer
The description is only "Wraps a fetch call." The second line starts with @, so the parser treats "@retry" as an unknown block tag whose text is "is handled by the caller." Reword it, for example "Retries are handled by the caller."
Exercise
Why does this comment cause a syntax error, and how do you fix it? "/ Removes files matching build//.tmp /"
Show answer
The sequence "/" inside "build//.tmp" closes the comment early, so ".tmp /" is parsed as code. Escape the slash ("build/*\/.tmp") or describe the pattern in words.
Exercise
You write a JSDoc comment, then a console.log line, then the function declaration. Which code does the comment document?
Show answer
It documents the console.log statement, because a comment attaches to whatever comes directly after it. Move the comment so it sits immediately above the function declaration.