Skip to content
jshacks.dev
Fundamentals

Comments and Documentation With JSDoc a Practical Guide

When to comment JavaScript and how to document it with JSDoc: param, returns, throws, typedef and template tags, ts-check type checking and generated docs.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, TypeScript, Node.js and Vite logos.

A comment is a promise that the code below it does what the comment says, and a promise that nobody checks is worth little. JavaScript gives you two ways to attach explanation to code: ordinary comments for the human reading a function, and JSDoc comments, which are structured enough for editors and tools to read as well. Used well, JSDoc does something comments alone cannot: it documents the types of a language that has none, and an editor or the TypeScript compiler can check calls against those types without you changing a line of JavaScript. This post covers what a comment should say and what it should leave out, the JSDoc tags worth knowing, how to describe object shapes and generic functions, how to turn on type checking from the comments, how to generate documentation, and the mistakes that make comments lie. The examples run on Node.js 24.

What a comment is for

The code says what happens. A comment should say why, and anything a reader cannot recover from the code alone: a constraint, a trade-off, a link to the bug that explains an odd line.

JavaScript
// Bad: repeats the code.
// Increment i by 1.
let i = 0;
i += 1;

// Good: records a reason the code cannot show.
// The payment API rounds every line to whole cents before summing, so we do the same.
function roundMoney(value) {
  const rounded = Math.round(value * 100) / 100;
  return Number.isInteger(value * 100) ? value : rounded;
}

console.log(roundMoney(2.005), roundMoney(10));
Text
2 10

The first comment adds nothing, because the line says it already. The second explains a decision that would otherwise look like a bug to a reader who "fixes" it. We delete comments that restate code, rewrite code that needs a comment to be understood, and keep the ones that carry information. Commented-out code is the worst kind: it will not run, nobody will remove it, and version control already remembers it. A TODO should name an owner or an issue, so it can be found and closed.

The JSDoc comment

A JSDoc comment starts with /** and sits directly above the thing it describes. Tags beginning with @ give structured facts.

JavaScript
/**
 * Splits a full name into first and last parts.
 *
 * @param {string} fullName - A name such as "Ada Lovelace".
 * @param {string} [separator=" "] - What separates the parts.
 * @returns {{ first: string, last: string }} The two parts.
 * @throws {TypeError} If `fullName` is not a string.
 * @example
 * splitName("Ada Lovelace"); // { first: "Ada", last: "Lovelace" }
 */
function splitName(fullName, separator = " ") {
  if (typeof fullName !== "string") {
    throw new TypeError("splitName: fullName must be a string");
  }
  const [first, ...rest] = fullName.split(separator);
  return { first, last: rest.join(separator) };
}

console.log(splitName("Ada Lovelace"));
console.log(splitName("Grace Brewster Murray Hopper"));

try {
  splitName(42);
} catch (error) {
  console.log(error.name);
}
Text
{ first: 'Ada', last: 'Lovelace' }
{ first: 'Grace', last: 'Brewster Murray Hopper' }
TypeError

The first line of the comment is a summary. The tag @param names a parameter with its type in braces, square brackets around the name mark it as optional, and the =" " after it records the default. @returns describes the result, @throws lists errors a caller may need to handle, and @example shows usage. An editor reads this and shows it as a tooltip when you hover over a call, which is where most people see it. Write the description in the same terms a caller would use, and do not repeat the type in prose.

Describing shapes with typedef

An object parameter with several fields needs a named description, and @typedef provides it.

JavaScript
/**
 * @typedef {object} User
 * @property {number} id - Unique identifier.
 * @property {string} name - Display name.
 * @property {string[]} [roles] - Optional list of roles.
 */

/**
 * @param {User} user
 * @returns {string}
 */
function describeUser(user) {
  const roles = user.roles?.join(", ") ?? "none";
  return `${user.name} (#${user.id}) roles: ${roles}`;
}

console.log(describeUser({ id: 1, name: "Ada", roles: ["admin", "editor"] }));
console.log(describeUser({ id: 2, name: "Grace" }));
Text
Ada (#1) roles: admin, editor
Grace (#2) roles: none

The type User is defined once and used wherever a user is expected, so a change to the shape happens in one place. The square brackets around roles mark that property as optional. This is the JavaScript counterpart of an interface in TypeScript, and tools that understand JSDoc treat them the same way.

Generic functions with template

A function that works for any type, and returns the same type it was given, uses @template.

JavaScript
/**
 * Returns the first item of a list, or a fallback.
 *
 * @template T
 * @param {T[]} items
 * @param {T} fallback
 * @returns {T}
 */
function firstOr(items, fallback) {
  return items.length > 0 ? items[0] : fallback;
}

console.log(firstOr([10, 20], 0), firstOr([], 0), firstOr(["a"], "none"));
Text
10 0 a

T stands for whatever type the call uses. With numbers in the array and a number fallback, the result is a number, and with strings it is a string. An editor that reads the tag will complain if you pass an array of numbers and a string fallback, since they disagree on T. A function that is called with mixed types needs a union, @param {Array<number | string>} items, and no template.

Type checking JavaScript from JSDoc

The comments become checked types when the TypeScript compiler reads them. Add one line to a file, or one setting to the project.

JavaScript
// @ts-check

/**
 * @param {number} price
 * @param {number} quantity
 * @returns {number}
 */
function total(price, quantity) {
  return price * quantity;
}

total("5", 3);
Text
file.js(12,7): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Running the compiler with npx tsc --allowJs --checkJs --noEmit reports the call on the last line, without changing or emitting any code. The code still runs as plain JavaScript, and "5" * 3 would silently produce 15 at run time, which is the mistake the check catches. A tsconfig.json with "checkJs": true turns the check on for a whole project, and // @ts-nocheck and // @ts-ignore turn it off for a file or a line. The result is much of TypeScript's safety without a build step, which suits scripts, small libraries and projects that want to stay in plain JavaScript.

Other tags worth knowing

TagUse
@type {T}Declare the type of a variable: /** @type {Map<string, number>} */
@callbackName a function type used by several parameters
@deprecatedMark an API as discouraged, with a reason and a replacement
@seePoint to a related function, a page or a specification
@sinceRecord the version that introduced an API
@private, @protectedMark visibility for tools, since JavaScript lacks the keywords
@overrideMark a method that replaces a parent method
@satisfiesCheck a value against a type without widening it
@importImport a type from another file for use in comments
JavaScript
/**
 * @callback Predicate
 * @param {number} value
 * @returns {boolean}
 */

/**
 * @param {number[]} values
 * @param {Predicate} test
 * @returns {number[]}
 */
function keep(values, test) {
  return values.filter(test);
}

/** @deprecated Use {@link keep} instead. */
function filterNumbers(values, test) {
  return keep(values, test);
}

console.log(keep([1, 2, 3, 4], (n) => n % 2 === 0));
console.log(filterNumbers([1, 2, 3, 4], (n) => n > 2));
Text
[ 2, 4 ]
[ 3, 4 ]

A @callback names a function shape so that the same description is not repeated on every parameter. An editor draws a line through filterNumbers at every call site because of @deprecated, and the {@link keep} inline tag is clickable.

Generating documentation

The jsdoc tool reads the comments and writes a website, and typedoc does the same with a more modern output when you have TypeScript or JSDoc types.

Shell
npx jsdoc src -r -d docs
npx typedoc --entryPoints src/index.js --out docs

Documentation generated from comments is only as good as the comments. Public functions, exported types and configuration options deserve full descriptions with examples, and internal helpers do not need them. A generated reference does not replace a guide that explains how the pieces fit together, and it does not replace a README that shows a first use.

Keep comments true

A comment that no longer matches the code is worse than none, and it happens whenever the code changes and the comment does not.

JavaScript
/**
 * Returns the price including 10% tax.
 * @param {number} price
 * @returns {number}
 */
function priceWithTax(price) {
  return price * 1.2;
}

console.log(priceWithTax(100));
Text
120

The comment says 10 percent and the code uses 20 percent, and a caller who trusts the comment builds a wrong invoice. Nothing in JavaScript catches the mismatch. The defenses are small: keep the comment next to the code it describes, change both in one commit, prefer to put numbers in named constants such as TAX_RATE so the code reads for itself, and let @ts-check verify the parts of the comment it can, which are the types.

A mistake we hit: documenting the type wrongly

JavaScript
// @ts-check

/**
 * @param {string[]} names
 * @returns {string}
 */
function initials(names) {
  return names.map((name) => name[0]).join("");
}

console.log(initials(["Ada", "Grace"]));

try {
  initials("Ada");
} catch (error) {
  console.log(error.name);
}
Text
AG
TypeError

At run time, passing a string where an array was documented fails with a TypeError, because a string has no map method, and only on the line that is executed. The type checker reports the same mistake before the program runs, with the exact argument and the type it expected, which is why we enable it. The lesson from our own code: types in comments are documentation until a tool reads them, and from that day they are tests.

Choosing between the approaches

You wantUse
To explain a decision or a constraintA plain // comment, written as a reason
To describe a public function for callersA JSDoc block with @param and @returns
To check calls against typesJSDoc types, and // @ts-check or checkJs
To name an object shape@typedef
A reusable generic function@template
A browsable referencejsdoc or typedoc
Full static typingTypeScript source files

Practical rules we follow

Write comments that say why. Delete commented-out code. Document public functions with JSDoc, including thrown errors and an example. Name shapes with @typedef. Turn on checkJs so the comments are verified. Keep the description and the code in one commit. Use named constants in place of numbers that need a comment. And treat a comment that is out of date as a bug.

Where JSDoc stops

JSDoc types are less expressive than TypeScript's: complex conditional and mapped types are awkward or impossible, and the syntax inside comments gets heavy. Large projects with many contributors usually move to .ts files, and JSDoc types remain a good fit for scripts, libraries that ship plain JavaScript, and gradual adoption. JSDoc also does not enforce anything at run time: a wrong type still runs unless you check. The reference is in the JSDoc documentation and the TypeScript handbook on JSDoc in JavaScript files.

Taggedjsdoc
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.